Ideas:
- Make a note of the position of the first non-empty character temp1, note the number of space_count_head and the number of trailing spaces space_count_tail.
- Total number of spaces length_new=space_count_head+space_count_tail;
- Copy the original string with the Temp1 as the starting position and the length of length_new to the source string.
The source code is as follows:
voidStripspace (CharStr[],intlength) { if(Str==null)return; Char*temp =str; intLast = length-1; intSpace_count_head =0; intSpace_count_tail =0; while(*temp==' ') {Space_count_head++; Temp++; } while(str[last]==' ') {Space_count_tail++; Last--; } intLength_new = length-space_count_head-Space_count_tail; intLen =length_new; Char*ret =str; while(length_new>0) { *str++= *temp++; Length_new--; } Ret[len]=' /';}
The main function is as follows:
intMain () {CharStr[] ="Hello World"; Char*p =str; cout<<"before strip:"<<Endl; cout<<"Str is"<<Endl; cout<< Str <<Endl; cout<<"Before:strlen (str)"<< strlen (str) <<Endl; intLength =strlen (str); Stripspace (str,length); cout<<"After strip:"<<Endl; cout<<"Str is"<<Endl; cout<< Str <<Endl; cout<<"After:strlen (str)"<< strlen (str) <<Endl; return 0;}
At first I defined the original string as: char *str = "Hello World" and found that STR could not be modified on-site in the called function, such as str[1] = ' d ' is not allowed.
Another long-time bug is the last add ' to ' on the STR, str[len]= ' ", in fact, the location of STR in the original copy of the time has been changed, this will produce a wild pointer, so should note the starting position of Str.
Remove whitespace from string header and trailing