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

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

    Hacked off of Cplusplus.com

    std::string choppa(const std::string &t, const std::string &ws)
    {
        std::string str = t;
        size_t found;
        found = str.find_last_not_of(ws);
        if (found != std::string::npos)
            str.erase(found+1);
        else
            str.clear();            // str is all whitespace
    
        return str;
    }
    

    This works for the null case as well. :-)

提交回复
热议问题