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:

void Trim (String &s) {    if (!s.empty ())    {        s.erase (0,s.find_first_not_of (""));        S.erase (S.find_last_not_of ("") + 1);}    } Remove the leading and trailing spaces

  

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

void Trim (string &s) {/    *    if (!s.empty ())    {        s.erase (0,s.find_first_not_of (""));        S.erase (S.find_last_not_of ("") + 1);    }    */    int index = 0;    if (!s.empty ())    {        while (index = S.find (', index))! = String::npos)        {            s.erase (index,1);        }    }} Remove all spaces

  

The test code is as follows:

int main () {       cout << "-------------------------------------" << Endl;    String pri = "  7ter   , jdhfd iere*-ddw     jjdjjdj     ";    cout << "private string is: \" "<< pri <<" \ "" << Endl;    Trim (PRI);    cout << "After string is: \" "<< pri <<" \ "" << Endl;    cout << "-------------------------------------" << Endl;    return 0;} Test code

  

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.