What's the best way to trim std::string?

后端 未结 30 2915
无人及你
无人及你 2020-11-21 22:13

I\'m currently using the following code to right-trim all the std::strings in my programs:

std::string s;
s.erase(s.find_last_not_of(\" \\n\\r\\         


        
30条回答
  •  逝去的感伤
    2020-11-21 22:37

    An elegant way of doing it can be like

    std::string & trim(std::string & str)
    {
       return ltrim(rtrim(str));
    }
    

    And the supportive functions are implemented as:

    std::string & ltrim(std::string & str)
    {
      auto it =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace(ch , std::locale::classic() ) ; } );
      str.erase( str.begin() , it);
      return str;   
    }
    
    std::string & rtrim(std::string & str)
    {
      auto it =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace(ch , std::locale::classic() ) ; } );
      str.erase( it.base() , str.end() );
      return str;   
    }
    

    And once you've all these in place, you can write this as well:

    std::string trim_copy(std::string const & str)
    {
       auto s = str;
       return ltrim(rtrim(s));
    }
    

提交回复
热议问题