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\t")+1);
It works fine, but I wonder if there are some end-cases where it might fail?
Of course, answers with elegant alternatives and also left-trim solution are welcome.
Best Answer
EDIT Since c++17, some parts of the standard library were removed. Fortunately, starting with c++11, we have lambdas which are a superior solution.
Thanks to https://stackoverflow.com/a/44973498/524503 for bringing up the modern solution.
Original answer:
I tend to use one of these 3 for my trimming needs:
They are fairly self-explanatory and work very well.
EDIT: BTW, I have
std::ptr_fun
in there to help disambiguatestd::isspace
because there is actually a second definition which supports locales. This could have been a cast just the same, but I tend to like this better.EDIT: To address some comments about accepting a parameter by reference, modifying and returning it. I Agree. An implementation that I would likely prefer would be two sets of functions, one for in place and one which makes a copy. A better set of examples would be:
I am keeping the original answer above though for context and in the interest of keeping the high voted answer still available.