Using Boost's string algorithms would be easiest:
#include <boost/algorithm/string.hpp>
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.