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

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

    With C++11 also came a regular expression module, which of course can be used to trim leading or trailing spaces.

    Maybe something like this:

    std::string ltrim(const std::string& s)
    {
        static const std::regex lws{"^[[:space:]]*", std::regex_constants::extended};
        return std::regex_replace(s, lws, "");
    }
    
    std::string rtrim(const std::string& s)
    {
        static const std::regex tws{"[[:space:]]*$", std::regex_constants::extended};
        return std::regex_replace(s, tws, "");
    }
    
    std::string trim(const std::string& s)
    {
        return ltrim(rtrim(s));
    }
    

提交回复
热议问题