Hello Donald,
What's the best way to remove trailing whitespace from a string? For
example: "John C. Doe \t" would become "John C. Doe". Thanks.
If you have to deal with different locales and/or wide-character
strings, the following code might be useful:
template<class E, class T, class A> class C_IsNotSpace_
{
private:
const std::locale& loc;
public:
C_IsNotSpace_(const std::locale& l) : loc(l) { }
inline bool operator()(E ch) const { return !std::isspace(ch, loc); }
};
template<class E, class T, class A>
inline std::basic_string<E, T, A> TrimRight(
const std::basic_string<E, T, A>& str,
const std::locale& loc = std::locale())
{
using namespace std;
typedef basic_string<E, T, A> T_Str;
C_IsNotSpace_<E, T, A> isNotSpace(loc);
typename T_Str::const_reverse_iterator rb = str.rbegin();
typename T_Str::const_reverse_iterator re = str.rend();
typename T_Str::const_reverse_iterator last = find_if(rb, re,
isNotSpace);
return (last == re) ? T_Str() : T_Str(re.base(), last.base());
}
// You can use it like this:
string s1 = " My test string \n";
string s2 = TrimRight(s1);
Tilman