Remove whitespace from string header and trailing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.