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

后端 未结 30 3429
无人及你
无人及你 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条回答
  •  Happy的楠姐
    2020-11-21 22:49

    Yet another option - removes one or more characters from both ends.

    string strip(const string& s, const string& chars=" ") {
        size_t begin = 0;
        size_t end = s.size()-1;
        for(; begin < s.size(); begin++)
            if(chars.find_first_of(s[begin]) == string::npos)
                break;
        for(; end > begin; end--)
            if(chars.find_first_of(s[end]) == string::npos)
                break;
        return s.substr(begin, end-begin+1);
    }
    

提交回复
热议问题