C + + Removes the leading and trailing spaces and all spaces in a string

Source: Internet
Author: User

C + + Remove the first and last space is a reference to an article, but forget the article source, just skip it.

The code to remove the trailing spaces is as follows:

1 voidTrimstring&s)2 {3 4     if( !s.empty ())5     {6S.erase (0, S.find_first_not_of (" "));7S.erase (S.find_last_not_of (" ") +1);8     }9 Ten}
Remove the leading and trailing spaces

The code for removing all the spaces in the string is as follows:

1 voidTrimstring&s)2 {3     /*4 if (!s.empty ())5     {6 s.erase (0,s.find_first_not_of (""));7 s.erase (S.find_last_not_of ("") + 1);8     }9     */Ten     intindex =0; One     if( !s.empty ()) A     { -          while(Index = S.find (' ', index))! =string:: NPOs) -         { theS.erase (Index,1); -         } -     } -  +}
Remove all spaces

The test code is as follows:

1 intMain ()2 {3    4cout <<"-------------------------------------"<<Endl;5 6     stringPRI ="7ter, jdhfd iere*-ddw jjdjjdj";7cout <<"private string is: \ ""<< pri <<"\""<<Endl;8 Trim (PRI);9cout <<"After string is: \ ""<< pri <<"\""<<Endl;Ten  Onecout <<"-------------------------------------"<<Endl; A  -     return 0; -}
Test Code

Results such as:

C + + Removes the leading and trailing spaces and all spaces in a string

Related Article

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.