C++ Trimming Leading or Trailing Spaces

One can use one of the string methods find_last_not_of and find_first_not_of. What these methods do is that they return the index of the string where the character in that index does NOT match what you are looking for.

For example:

string str = " TEST STRING "; //there is a space in the beginning and end

cout << str.find_first_not_of(" ") << endl; //this line will return a 1, because thats the first thats not of a " "

To get rid of the leading and trailing spaces in that string, we can do this:

str = str.substr(str.find_first_not_of(" "));  //str will now be assigned "TEST STRING ", note that there is still a space at the end

str = str.substr(0, str.find_last_not_of(" ") + 1) //now the trailing space is removed.  a 1 is added because without it, we would get "TEST STRIN" instead.  the 1 ensures that only the space is removed

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s