c++ about removing spaces

Copyright statement: [This article is original by the blogger and may not be reproduced without the permission of the blogger] 

The experimental question, the function that needs to be done is

Input a string, remove all spaces in the string, and output the length of the string after removing spaces, you need to write the following function:

1. Write the function void input(char *str), the function of which is to input a string .

2. Write the function void trim(char *str), the function of which is to remove all spaces from a string.

3. Write the function void length(char *str, int *l), and use the pointer l to return the length of the string.

The main function is

1. Write the main function main to test the above functions. The code is as follows:

void main()

{

char str[100];

int l;

input(str);

trim(str);

cout<<"The string after triming is "<<str<<endl;

length(str,&l);

cout<<"The length of the string is "<<l<<endl;

}

2. The expected results are as follows:

 

 


These functions need to be implemented separately. So it is easy to write the input and length2 functions as

void input(char *str)
{
char *a;
a = str;// scanf("%s",a);cout<<"Please input a string:";cin>>a;





}

void length(char *str,int *l)
{
*l=strlen(str);/*printf("strlen(str)=%d\n",*l);*/

}

So I found a lot of whitespace deletion algorithms in the blog. The success is this function:

void trim(char *str)  
{  
    int len,k,i;  
    if (str == NULL)  
        return;  
    len = strlen(str);  
    k = 0;  
    for (i=0; i<len; i++)  
    {  
        if ((str[i] != ' ')&&(str[i] != '\n'))  
        {  
           str[k]=str[i];  
           k++;  
        }  
    }  
    str[k]='\0';  
    return;  

But the little details about the basics get stuck here for days.

The following operation results found that only the automatic acquisition after the previous string was controlled to fail. Finally stumbled across a note in a blog post

/* cout<<endl; If scanf is used to receive a string, the string must not contain spaces, otherwise a space will be used as the end character of the string. If you type hello world then scanf actually only gets the word hello. So if you want to receive spaces, you can use the gets() function. gets(str) is to read a string of characters ending with a carriage return, store them in the memory unit with str as the first address, and finally write the characters





end-of-string flag "\0 * /

I just found the right direction is not an algorithm error but an error in the input function, change cin>>a; to gets(str); and finally realize the function.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324885695&siteId=291194637