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\\
My solution based on the answer by @Bill the Lizard.
Note that these functions will return the empty string if the input string contains nothing but whitespace.
const std::string StringUtils::WHITESPACE = " \n\r\t";
std::string StringUtils::Trim(const std::string& s)
{
return TrimRight(TrimLeft(s));
}
std::string StringUtils::TrimLeft(const std::string& s)
{
size_t startpos = s.find_first_not_of(StringUtils::WHITESPACE);
return (startpos == std::string::npos) ? "" : s.substr(startpos);
}
std::string StringUtils::TrimRight(const std::string& s)
{
size_t endpos = s.find_last_not_of(StringUtils::WHITESPACE);
return (endpos == std::string::npos) ? "" : s.substr(0, endpos+1);
}