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

后端 未结 30 2953
无人及你
无人及你 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 22:57

    Using Boost's string algorithms would be easiest:

    #include 
    
    std::string str("hello world! ");
    boost::trim_right(str);
    

    str is now "hello world!". There's also trim_left and trim, which trims both sides.


    If you add _copy suffix to any of above function names e.g. trim_copy, the function will return a trimmed copy of the string instead of modifying it through a reference.

    If you add _if suffix to any of above function names e.g. trim_copy_if, you can trim all characters satisfying your custom predicate, as opposed to just whitespaces.

提交回复
热议问题