zoukankan      html  css  js  c++  java
  • 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;
    }
    
    测试代码
    

      

    结果如下图:

  • 相关阅读:
    hdu1242 Rescue BFS广搜 + 优先队列
    hdu 1430 魔板
    康托展开
    hdu 4394 Digital Square(bfs)
    hdu 1969 Pie
    KMP模板
    hdu 1846 Brave Game
    循环赛日程表
    hdu 1022 Train Problem I
    整数划分问题
  • 原文地址:https://www.cnblogs.com/ye-ming/p/9007624.html
Copyright © 2011-2022 走看看