How to trim a stdstring?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
std::string does not have a built-in trim() method. To trim whitespace from a std::string, write small helper functions using std::find_if with std::isspace, or use find_first_not_of and find_last_not_of with a whitespace character set. The standard approach takes about five lines of code and covers leading whitespace (left trim), trailing whitespace (right trim), or both.
How the Algorithm Works
Left Trim
ltrim uses std::find_if with a forward iterator to locate the first non-whitespace character. It then erases everything from the beginning of the string up to that position:
Right Trim
rtrim uses reverse iterators (rbegin, rend) to scan from the end of the string backward. It finds the last non-whitespace character, converts the reverse iterator to a forward iterator with .base(), and erases from that point to the end:
Combined Trim
trim calls ltrim first, then rtrim. Order does not matter, but trimming the left first means rtrim operates on a slightly shorter string.
Returning a Copy Instead of Mutating
Sometimes you want to preserve the original string. Return a copy by taking the string parameter by value:
Usage:
This version is convenient in function chains, logging, and anywhere mutation would be unexpected.
Alternative: Using find_first_not_of and find_last_not_of
An alternative approach uses std::string's member functions to find the first and last characters that are not in a given set:
This approach is arguably more readable because the whitespace character set is explicit and easy to modify. It also avoids the reverse-iterator-to-forward-iterator conversion that confuses some readers.
Trimming Specific Characters
The same find_first_not_of and find_last_not_of pattern works for trimming any set of characters:
Examples:
C++20 and C++23 Improvements
C++20 introduced std::ranges, which can make the trim slightly more expressive:
C++23 does not add a dedicated trim() method to std::string, so helper functions remain necessary.
Using std::string_view for Read-Only Trimming
If you only need to read the trimmed result without allocating a new string, std::string_view avoids the copy:
This is zero-allocation and works well in 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 |
The unsigned char Detail
In every example that uses std::isspace, the lambda parameter is unsigned char, not char. This is intentional. The C standard specifies that character classification functions like isspace accept unsigned char or EOF. Passing a signed char value greater than 127 (common in UTF-8 text) is undefined behavior:
This detail rarely causes visible bugs in ASCII-only codebases, which is why it gets overlooked. But it matters the moment your program processes text with accented characters, CJK text, or any other non-ASCII content.
Boost Alternative
If your project already uses Boost, the Boost.StringAlgo library provides ready-made trim functions:
Boost trim functions handle the unsigned char issue internally, so you do not need to worry about it.
Common Pitfalls
Forgetting to handle strings that are entirely whitespace causes find_first_not_of to return std::string::npos. If that return value is passed to substr without checking, the result is usually a garbage string or an exception. Always check for npos before computing the substring.
Using char instead of unsigned char in the isspace lambda is undefined behavior for non-ASCII input. The code may appear to work during testing with English text and then crash or misbehave with internationalized content.
Mixing in-place and copy-returning trim functions in the same codebase without clear naming conventions causes confusion. Establish a naming rule like trim() for in-place and trim_copy() for copy-returning, and apply it consistently.
Assuming std::isspace handles Unicode whitespace is incorrect. std::string stores bytes, and std::isspace only recognizes ASCII whitespace characters (space, tab, newline, carriage return, form feed, vertical tab). Unicode whitespace characters like the non-breaking space (U+00A0) or ideographic space (U+3000) require a Unicode-aware library such as ICU.
Creating trim helpers that are only used in one file but duplicated across the project is a maintenance issue. Put the helpers in a shared utility header so every module uses the same implementation.
Summary
std::stringhas no built-intrim(). Write small helpers usingstd::find_ifwithstd::isspaceorfind_first_not_of/find_last_not_of.- Choose between in-place mutation and copy-returning based on your use case, and name the functions to make the behavior obvious.
- Use
find_first_not_of/find_last_not_ofwhen you need to trim a custom set of characters. - Always use
unsigned charinstd::isspacelambdas to avoid undefined behavior with non-ASCII input. - Check for
std::string::nposwhen the input string might be entirely whitespace. - Consider
std::string_viewfor zero-allocation trimming in performance-sensitive parsers. - Use Boost
trimif your project already depends on Boost.
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 courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.