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\\
Here is a straight forward implementation. For such a simple operation, you probably should not be using any special constructs. The build-in isspace() function takes care of various forms of white characters, so we should take advantage of it. You also have to consider special cases where the string is empty or simply a bunch of spaces. Trim left or right could be derived from the following code.
string trimSpace(const string &str) {
if (str.empty()) return str;
string::size_type i,j;
i=0;
while (i0 && isspace(str[j])) --j; // the j>0 check is not needed
while (isspace(str[j])) --j
return str.substr(i, j-i+1);
}