C++去掉字符串中首尾空格和所有空格

c++去掉首尾空格是参考一篇文章的,但是忘记文章出处了,就略过吧。

去掉首尾空格的代码如下:

void trim(string &s)
{

    if( !s.empty() )
    {
        s.erase(0,s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
    }

}

去掉首尾空格

  

去掉字符串中所有空格的代码如下:

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);
        }
    }

}

去掉所有空格

  

测试代码如下:

int main()
{
   
    cout << "-------------------------------------" << endl;

    string pri = "  7ter   09, jdhfd iere*- ddw     jjdjjdj     ";
    cout << "private string is : "" << pri << """ << endl;
    trim(pri);
    cout << "after string is : "" << pri << """ << endl;

    cout << "-------------------------------------" << endl;

    return 0;
}

测试代码

  

结果如下图:

原文地址:https://www.cnblogs.com/ye-ming/p/9007624.html