How trim off the last few whitespace of a string?

The string my contain several words but I want to trim off any excess whitespace if any.

Is there a really simple way of doing this?
You could travel backwards in the string, count the whitespace characters that are occuring until you hit the first non-whitespace character, and then generate a substring with string::substr (http://www.cplusplus.com/reference/string/string/substr/ ) that doesn't contain those whitespace characters. Alternatively, you can also extract those strings using a stringstream (http://www.cplusplus.com/reference/iostream/stringstream/ ) - those ignore whitespace.
Try something like this:


1
2
3
4
5
6
7
8
9
string s="    \tTesting  \n\n\t   "; //replace with the name of your string

while(s.size()) {
                //the number 33 refers to ascii character 33... the first printable character :)
	if(s[0]<33) s.erase(s.begin()); //remove all leading whitespace
	else if(s[s.size()-1]<33) s.erase(s.size()-1); //remove all trailing whitespace
	else break;
}
cout << s;


edit: initialized string for testing
Last edited on
I use something like this to trim whitespace from around a std::string:
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * Remove surrounding whitespace from a std::string.
 * @param s The string to be modified.
 * @param t The set of characters to delete from each end
 * of the string.
 * @return The same string passed in as a parameter reference.
 */
std::string& trim(std::string& s, const char* t = " \t\n\r\f\v")
{
	s.erase(0, s.find_first_not_of(t));
	s.erase(s.find_last_not_of(t) + 1);
	return s;
}

If you just want to remove whitespace from the end of the string you could use:
 
s.erase(s.find_last_not_of(" \t\n\r\f\v") + 1);
Topic archived. No new replies allowed.