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

1. Using string::erase

The idea is to get the index of the first and last non-whitespace character using the std::string::find_first_not_of and std::string::find_last_not_of function respectively. Then erase the substring consisting of whitespace characters with the string::erase function.

Download  Run Code

 
Here’s an equivalent version using the std::find_if function.

Download  Run Code

2. Using string::substr

The idea here remains the same – find the index of the first and last character that isn’t whitespace using the std::string::find_first_not_of and std::string::find_last_not_of function respectively. Then return the substring between the two positions using the string::substr function. Note this results in a new string.

Download  Run Code

3. Using std::regex_replace

Another option to remove leading and trailing spaces from a string is using regular expressions. Starting with C++11, we can use the std::regex_replace function, as demonstrated below. Note that this results in a new string.

Download  Run Code

4. Using Boost

If you’re already using the Boost library, consider using the boost string algorithm boost::algorithm::trim. This solution is short and elegant, and modifies the string in-place. Here’s an example of its usage:

Download  Run Code

5. Using std::string_view

C++17 allows forming a string view of a character literal with the header <string_view>. After getting the string view, we can use the remove_prefix and remove_suffix functions to left trim and right trim the string. For example,

Download Code

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