Henry Poon's Blog

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. &amp;nbsp;a 1 is added because without it, we would get "TEST STRIN" instead.  the 1 ensures that only the space is removed

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Next Post

Previous Post

Leave a Reply

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

© 2024 Henry Poon's Blog

Theme by Anders Norén