remove trailing whitespace from string

D

Donald Canton

What's the best way to remove trailing whitespace from a string? For
example: "John C. Doe \t" would become "John C. Doe". Thanks.
 
K

Karl Heinz Buchegger

Donald said:
What's the best way to remove trailing whitespace from a string? For
example: "John C. Doe \t" would become "John C. Doe". Thanks.

By gooing to www.google.com, switching to the newsgroup archives
and doing some research.
A search string of "C++ trailing whitespace eliminate" comes
up with a lot of good hits.
 
V

Victor Bazarov

Donald Canton said:
What's the best way to remove trailing whitespace from a string? For
example: "John C. Doe \t" would become "John C. Doe". Thanks.

Something like

string::reverse_iterator it = somestring.rbegin();
while (it != somestring.rend() && isspace(*it))
{
somestring.erase(it);
it = somestring.rbegin();
}

That's if we're talking of 'string' type. For char array
you do

int lci = strlen(somestring) - 1;
while (lci >= 0 && isspace(somestring[lci])
somestring[lci--] = 0; // move the terminator there

Disclaimer: code wasn't tested.

V
 
J

John Harrison

Donald Canton said:
What's the best way to remove trailing whitespace from a string? For
example: "John C. Doe \t" would become "John C. Doe". Thanks.

This is untested code

const char* const whitespace = " \t\r\n\v\f";

s.erase(s.find_last_not_of(whitespace) + 1);

john
 
T

Tilman Kuepper

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top