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

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

    This version trims internal whitespace and non-alphanumerics:

    static inline std::string &trimAll(std::string &s)
    {   
        if(s.size() == 0)
        {
            return s;
        }
    
        int val = 0;
        for (int cur = 0; cur < s.size(); cur++)
        {
            if(s[cur] != ' ' && std::isalnum(s[cur]))
            {
                s[val] = s[cur];
                val++;
            }
        }
        s.resize(val);
        return s;
    }
    

提交回复
热议问题