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;
    }
    
    测试代码
    

      

    结果如下图:

  • 相关阅读:
    程序员数学
    [topcoder]FlowerGarden
    [leetcode]Trapping Rain Water
    [leetcode]Gray Code
    [leetcode]Unique Paths II
    hdu 4112 Break the Chocolate(ceil floor)
    【转】博弈-翻硬币游戏
    POJ 3710 Christmas Game
    hdu 3590 PP and QQ
    博弈进阶
  • 原文地址:https://www.cnblogs.com/ye-ming/p/9007624.html
Copyright © 2011-2022 走看看