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

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

    With C++17 you can use basic_string_view::remove_prefix and basic_string_view::remove_suffix:

    std::string_view trim(std::string_view s)
    {
        s.remove_prefix(std::min(s.find_first_not_of(" \t\r\v\n"), s.size()));
        s.remove_suffix(std::min(s.size() - s.find_last_not_of(" \t\r\v\n") - 1, s.size()));
    
        return s;
    }
    

    A nice alternative:

    std::string_view ltrim(std::string_view s)
    {
        s.remove_prefix(std::distance(s.cbegin(), std::find_if(s.cbegin(), s.cend(),
             [](int c) {return !std::isspace(c);})));
    
        return s;
    }
    
    std::string_view rtrim(std::string_view s)
    {
        s.remove_suffix(std::distance(s.crbegin(), std::find_if(s.crbegin(), s.crend(),
            [](int c) {return !std::isspace(c);})));
    
        return s;
    }
    
    std::string_view trim(std::string_view s)
    {
        return ltrim(rtrim(s));
    }
    

提交回复
热议问题