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:

1void Trim (string &s)  2 { 3  4 if (! S.empty ())  5  { 6 s.erase ( Span style= "COLOR: #800080" >0,s.find_first_not_of ( "" Span style= "color: #000000"));  7 s.erase (s.find_last_not_of ( " 1);  8 } 9 10}    

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

1void Trim (String &S2{3/*4if (!s.empty ())5{6S.erase (0,s.find_first_not_of (""));7S.erase (S.find_last_not_of ("") + 1);8}9*/10int index =0; if (! S.empty ()) 12  {13 while ((index = s.find ( '  ", index)) ! = string::npos) 14  {15 s.erase (Index,1); 16 }17 }18 19}       

The test code is as follows:

1IntMain ()2{34 cout <<"-------------------------------------"<<Endl56String pri ="7ter, JDHFD iere*-ddw JJDJJDJ";7 cout <<"private string is: \ ""<< pri <<"\""<<Endl 8  trim (PRI);  9 cout < <  "after string is: \"  " << pri <<  "\"  Endl; 11 cout <<  "------ ------------------------------- "<< Endl;12 13 return 0;                 

Results such as:

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

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.