Funny how a trivial task like trimming trailing spaces in C++ gets a bit harder if you insist on using STL (standard template library). But the good thing is, the internet is there and Google is so good at finding the right answer if you ask the right question. And after reading some samples, I found the solution.

Here’s the actual code that I used.
inline string trim_right (const string & s)
{
size_t found;
string whitespaces (" tnr");

string str (s);
found=str.find_last_not_of(whitespaces);
if (found!=string::npos){
str.erase(found+1);
}
else{
str.clear();
}
return str;
}

here’s a sample function call

string str1="lorem ipsum dolor ";
string str2=" ";
str2=trim_right(str1);
cout << "->|" << str2.c_str() << "|<-";

Here's the shorter version of the code.

str=str.find_last_not_of(" tnr");

Actually, there could be a ton of other implementation but that's what I'm using. If you know a better way, let me know.

Comments are closed.

Post Navigation