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

后端 未结 30 3411
无人及你
无人及你 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:42

    http://ideone.com/nFVtEo

    std::string trim(const std::string &s)
    {
        std::string::const_iterator it = s.begin();
        while (it != s.end() && isspace(*it))
            it++;
    
        std::string::const_reverse_iterator rit = s.rbegin();
        while (rit.base() != it && isspace(*rit))
            rit++;
    
        return std::string(it, rit.base());
    }
    

提交回复
热议问题