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.
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
elseif(s[s.size()-1]<33) s.erase(s.size()-1); //remove all trailing whitespace
elsebreak;
}
cout << s;
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, constchar* 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: