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

This site uses Akismet to reduce spam. Learn how your comment data is processed.