This post will discuss how to remove leading and trailing spaces from a string in C++. In other words, trim a string in C++.

1. Using find_first_not_of() with find_last_not_of() function

We can use a combination of string’s find_first_not_of() and find_last_not_of() functions to remove leading and trailing spaces from a string in C++ by finding the index of the first and last non-whitespace character and pass the index to substr() functions to trim the string.

Download  Run Code

2. Using std::find_if function

Another efficient solution is to use std::find_if to remove leading and trailing spaces, as shown below:

Download  Run Code

3. Custom function

We can also write our own routine for this, as shown below:

Download  Run Code

4. Using std::regex_replace function

With C++11, we can also use std::regex_replace for this. This is demonstrated below:

Download  Run Code

5. Using Boost Library

Another good alternative is to use Boost Library. It provides trim_right(), trim_left() and trim() functions.

Download Code

That’s all about removing leading and trailing spaces in C++.