C++ Programming
String Manipulation
Coding Tutorials
Programming Tips
C++ Strings

How to trim a std::string (leading and trailing whitespace) in C++

Codemia Knowledge Hub ·

std::string has no built-in trim() method. Write small helpers with std::find_if and std::isspace, or use find_first_not_of and find_last_not_of with a set of whitespace characters. These cover leading whitespace (left trim), trailing whitespace (right trim) or both:

cpp
1#include <algorithm>
2#include <cctype>
3#include <string>
4
5// Trim from the left (in place)
6void ltrim(std::string& s) {
7    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
8        [](unsigned char ch) { return !std::isspace(ch); }));
9}
10
11// Trim from the right (in place)
12void rtrim(std::string& s) {
13    s.erase(std::find_if(s.rbegin(), s.rend(),
14        [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end());
15}
16
17// Trim both ends (in place)
18void trim(std::string& s) {
19    ltrim(s);
20    rtrim(s);
21}

How the in-place version works

Left trim

ltrim uses std::find_if with a forward iterator to find the first non-whitespace character, then erases everything from the start of the string up to it:

cpp
1// Before: "   hello"
2//          ^  ^--- find_if stops here (first non-space)
3//          |------ erase from here to the found position
4// After:  "hello"

Right trim

rtrim scans backward with reverse iterators (rbegin, rend) to find the last non-whitespace character, converts the reverse iterator to a forward iterator with .base(), and erases from there to the end:

cpp
1// Before: "hello   \n"
2//               ^-------- find_if (reverse) stops here
3//               .base()--> erase from here to end
4// After:  "hello"

Both ends

trim calls ltrim and then rtrim. The order does not matter, but trimming the left first means rtrim works on a slightly shorter string.

Returning a trimmed copy

To keep the original string intact, take the parameter by value and return it:

cpp
1#include <algorithm>
2#include <cctype>
3#include <string>
4
5std::string trim_copy(std::string s) {
6    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
7        [](unsigned char ch) { return !std::isspace(ch); }));
8    s.erase(std::find_if(s.rbegin(), s.rend(),
9        [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end());
10    return s;
11}

Usage:

cpp
1std::string original = "  data  ";
2std::string cleaned = trim_copy(original);
3// original is still "  data  "
4// cleaned is "data"

This version is handy in function chains, logging, and anywhere mutation would be unexpected. If a codebase has both kinds, name them clearly, for example trim() for in place and trim_copy() for the copy, and stick to it.

Using find_first_not_of and find_last_not_of

std::string's own member functions can find the first and last characters that are not in a given set:

cpp
1#include <string>
2
3std::string trim_v2(const std::string& s) {
4    const std::string whitespace = " \t\n\r\f\v";
5    auto start = s.find_first_not_of(whitespace);
6    if (start == std::string::npos) {
7        return "";
8    }
9    auto end = s.find_last_not_of(whitespace);
10    return s.substr(start, end - start + 1);
11}

The whitespace set is explicit and easy to change, and there is no reverse-iterator conversion to puzzle over, so many readers find this version clearer.

Check for std::string::npos as this code does. A string that is entirely whitespace makes find_first_not_of return npos, and passing that to substr unchecked usually gives a garbage string or an exception.

Trimming specific characters

The same pattern trims any set of characters:

cpp
1std::string trim_chars(const std::string& s, const std::string& chars) {
2    auto start = s.find_first_not_of(chars);
3    if (start == std::string::npos) {
4        return "";
5    }
6    auto end = s.find_last_not_of(chars);
7    return s.substr(start, end - start + 1);
8}

Examples:

cpp
1// Remove surrounding quotes
2std::string a = trim_chars("\"hello\"", "\"");
3// a == "hello"
4
5// Remove leading/trailing slashes
6std::string b = trim_chars("/api/v1/users/", "/");
7// b == "api/v1/users"
8
9// Remove multiple character types
10std::string c = trim_chars("##--title--##", "#-");
11// c == "title"

C++20 ranges version

C++20's std::ranges makes the trim slightly more expressive:

cpp
1#include <algorithm>
2#include <cctype>
3#include <ranges>
4#include <string>
5
6std::string trim_ranges(std::string s) {
7    auto not_space = [](unsigned char ch) { return !std::isspace(ch); };
8
9    // Drop leading whitespace
10    auto left = std::ranges::find_if(s, not_space);
11    s.erase(s.begin(), left);
12
13    // Drop trailing whitespace
14    auto right = std::ranges::find_if(s | std::views::reverse, not_space);
15    s.erase(right.base(), s.end());
16
17    return s;
18}

C++23 does not add a trim() method to std::string either, so helper functions are still needed.

Trimming without allocating using std::string_view

If you only need to read the trimmed result, std::string_view avoids the copy:

cpp
1#include <string_view>
2#include <cctype>
3
4std::string_view trim_view(std::string_view sv) {
5    while (!sv.empty() && std::isspace(static_cast<unsigned char>(sv.front()))) {
6        sv.remove_prefix(1);
7    }
8    while (!sv.empty() && std::isspace(static_cast<unsigned char>(sv.back()))) {
9        sv.remove_suffix(1);
10    }
11    return sv;
12}

This allocates nothing and suits parsers that process large amounts of text. The returned string_view is only valid as long as the original string exists.

Comparison of approaches

ApproachMutates originalAllocatesCustom charsReadability
std::find_if + erase (in place)YesNoRequires lambda changeModerate
std::find_if + erase (copy)NoYesRequires lambda changeModerate
find_first_not_of + substrNoYesPass as string parameterHigh
std::string_view trimNoNoRequires manual loopModerate
Boost boost::trimYesNoVia boost::trim_ifHigh

Why the lambda takes unsigned char

Every example that calls std::isspace uses an unsigned char parameter, not char. Character classification functions like isspace accept unsigned char values or EOF. Passing a signed char above 127 (common in UTF-8 text) is undefined behavior:

cpp
1// Dangerous: char may be negative on some platforms
2[](char ch) { return !std::isspace(ch); }      // UB for non-ASCII
3
4// Correct: cast to unsigned char
5[](unsigned char ch) { return !std::isspace(ch); } // well-defined

This rarely shows up in ASCII-only code, which is why it gets overlooked. It matters as soon as your program handles accented characters, CJK text or any other non-ASCII content: code that passed tests with English text can crash or misbehave.

std::isspace does not know Unicode whitespace

std::string stores bytes, and std::isspace only recognizes ASCII whitespace (space, tab, newline, carriage return, form feed, vertical tab). Unicode whitespace such as the non-breaking space (U+00A0) or the ideographic space (U+3000) needs a Unicode-aware library such as ICU.

Boost alternative

If your project already uses Boost, Boost.StringAlgo has ready-made trim functions:

cpp
1#include <boost/algorithm/string/trim.hpp>
2
3std::string s = "  hello  ";
4
5boost::trim(s);            // in-place trim
6auto copy = boost::trim_copy(s); // returns trimmed copy
7boost::trim_left(s);       // trim left only
8boost::trim_right(s);      // trim right only
9
10// Trim specific characters
11boost::trim_if(s, boost::is_any_of("/-"));

Boost's trim functions handle the unsigned char issue internally.

Whichever version you pick, put the helpers in a shared utility header so every module uses the same implementation instead of a copy per file.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms