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:
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:
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:
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:
Usage:
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:
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:
Examples:
C++20 ranges version
C++20's std::ranges makes the trim slightly more expressive:
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:
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
| Approach | Mutates original | Allocates | Custom chars | Readability |
std::find_if + erase (in place) | Yes | No | Requires lambda change | Moderate |
std::find_if + erase (copy) | No | Yes | Requires lambda change | Moderate |
find_first_not_of + substr | No | Yes | Pass as string parameter | High |
std::string_view trim | No | No | Requires manual loop | Moderate |
Boost boost::trim | Yes | No | Via boost::trim_if | High |
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:
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:
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.
Related reading
- How to use a tensorflow graph in opencv c?
- How to use AWS SDK C XRay in a AWS Lambda Layer implemented in C called by a Lambda function in Python?
- How to use lower_boundupper_bound to find position of any number in array?
- How to use null in switch
- How to work with TF Lite library in a c project
- How to write a range-v3 action for random_shuffle?
- How to write iOS app purely in C
- Howto create combinations of several vectors without hardcoding loops in C?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseData 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.