std::string has no trim, so write a three-line one: find the first and last characters that are not whitespace with s.find_first_not_of(" \t\n\v\f\r") and s.find_last_not_of(...), then take the substr between them. Return {} when find_first_not_of gives npos: the input was empty or all whitespace. Taking and returning a std::string_view trims without copying.
Trimming is one of the most-asked C++ string questions because the standard library never added a trim, not even in C++23. The building blocks are all there, and the answers differ in three ways: whether the function copies, edits the string in place or returns a view; how it handles a string that is all whitespace; and what it counts as whitespace. The sections below cover the string_view version, the classic in-place erase, a C++20 ranges pipeline, removing inner spaces, and the invisible Unicode characters a byte-level trim misses. Each example runs on this page: hit Run, then edit the code and run it again.
1find_first_not_of and find_last_not_ofRecommended
find_first_not_of(chars) returns the index of the first character that is not in chars, and find_last_not_of the last one, so the trimmed text is everything from the first to the last. Writing it on std::string_view means the function accepts a std::string, a literal or another view, and returns a window into the input without allocating. The chars parameter makes the same function strip any set of characters, and ltrim and rtrim are each half of it.
#include <iostream> #include <string> #include <string_view> // The six characters std::isspace counts as whitespace in the "C" locale constexpr std::string_view whitespace = " \t\n\v\f\r"; // A view of s without leading and trailing whitespace: nothing is copied std::string_view trim(std::string_view s, std::string_view chars = whitespace) { std::size_t first = s.find_first_not_of(chars); if (first == std::string_view::npos) { return {}; // empty, or nothing but whitespace } std::size_t last = s.find_last_not_of(chars); return s.substr(first, last - first + 1); } std::string_view ltrim(std::string_view s, std::string_view chars = whitespace) { std::size_t first = s.find_first_not_of(chars); return first == std::string_view::npos ? std::string_view{} : s.substr(first); } std::string_view rtrim(std::string_view s, std::string_view chars = whitespace) { std::size_t last = s.find_last_not_of(chars); return last == std::string_view::npos ? std::string_view{} : s.substr(0, last + 1); } int main() { // Brackets show exactly where each result starts and ends std::string input = "\t hello, world \r\n"; std::cout << '[' << trim(input) << "]\n"; std::string padded = " both sides "; std::cout << '[' << ltrim(padded) << "]\n"; std::cout << '[' << rtrim(padded) << "]\n"; // Only the ends: inner spaces stay std::cout << '[' << trim(" a b ") << "]\n"; // All whitespace or empty: an empty result, not an exception std::cout << '[' << trim(" \t\n ") << "] [" << trim("") << "]\n"; // Any set of characters, not only whitespace std::cout << '[' << trim("--==title==--", "-=") << "]\n"; // Need a string you can keep or change? Copy the view into one std::string clean(trim(input)); clean += '!'; std::cout << clean << " (" << clean.size() << " chars)\n"; }
Output
The tab, spaces, \r and \n all go: [hello, world]. ltrim and rtrim print [both sides ] and [ both sides], and inner runs are never touched: [a b]. The npos check is what makes all-whitespace and empty input safe, [] []: without it, find_last_not_of also returns npos and the arithmetic goes wrong. With a custom set, "--==title==--" becomes [title]. The one rule a view brings is lifetime: the result points into the input, so auto v = trim(std::string(" x ")); dangles once the temporary dies. Copy into a std::string when you keep it, as the last line does: hello, world! (13 chars).
2In place with erase and find_if_not
The most-voted answer on Stack Overflow trims a std::string& in place: find_if_not with std::isspace finds the first non-space character, and erase removes everything before it. For the right end the search runs on reverse iterators, and .base() converts the result back for erase. Older versions of that answer use std::not1(std::ptr_fun<int, int>(std::isspace)). Those adaptors are gone from the standard (ptr_fun since C++17, not1 since C++20). GCC still compiles them with two deprecation warnings, other compilers reject them, so use a lambda or a small function.
#include <algorithm> #include <cctype> #include <iostream> #include <string> // std::isspace wants an unsigned char value: a plain char can be negative // (every byte of a UTF-8 'é' is), and passing a negative value is undefined bool is_space(unsigned char ch) { return std::isspace(ch) != 0; } // Erase from the start up to the first non-space character void ltrim(std::string& s) { s.erase(s.begin(), std::find_if_not(s.begin(), s.end(), is_space)); } // Search backwards with reverse iterators; base() converts the result // to a normal iterator just past the last non-space character void rtrim(std::string& s) { s.erase(std::find_if_not(s.rbegin(), s.rend(), is_space).base(), s.end()); } void trim(std::string& s) { rtrim(s); // right first, so ltrim has fewer characters to shift ltrim(s); } // A copying version for when the original must not change std::string trimmed(std::string s) { trim(s); return s; } int main() { std::string s = " \tcafé au lait\r\n"; trim(s); std::cout << '[' << s << "] " << s.size() << " bytes\n"; std::string line = " keep me "; std::string copy = trimmed(line); std::cout << '[' << line << "] -> [" << copy << "]\n"; std::string blank = " \t\n "; trim(blank); std::cout << "blank: [" << blank << "] empty: " << std::boolalpha << blank.empty() << '\n'; }
Output
The string itself changes: [café au lait] 13 bytes, where é takes two bytes in UTF-8. trimmed takes its argument by value, so it works on a copy and the original stays padded: [ keep me ] -> [keep me]. An all-whitespace string needs no special case here, because find_if_not just returns the end: blank: [] empty: true. The unsigned char parameter is not decoration. char is signed on most platforms, the bytes of é are negative as char, and std::isspace on a negative value other than EOF is undefined behaviour. Passing ::isspace directly as the predicate compiles but skips that conversion, and std::isspace does not compile at all here: <locale> overloads the name, and GCC reports <unresolved overloaded function type>.
3C++20 ranges: views::drop_while
With C++20 ranges, a trim is a pipeline: drop whitespace from the front, reverse, drop it from the front again, and reverse back. The view is lazy, so nothing is scanned until the std::string is built from its iterators. It reads well, but it is longer than section 1 and builds a new string every time. For one end only, std::ranges::find_if_not gives the position directly.
#include <cctype> #include <iostream> #include <ranges> #include <string> #include <string_view> std::string trim(std::string_view s) { auto is_space = [](unsigned char ch) { return std::isspace(ch) != 0; }; // Drop spaces from the front, flip, drop them from the (new) front, // flip back. Lazy: nothing happens until the string is built below auto view = s | std::views::drop_while(is_space) | std::views::reverse | std::views::drop_while(is_space) | std::views::reverse; return std::string(view.begin(), view.end()); } int main() { std::cout << '[' << trim("\n ranges are lazy \t") << "]\n"; std::cout << '[' << trim(" ") << "]\n"; // std::ranges algorithms work too: find the first non-space directly std::string_view text = " left only"; auto it = std::ranges::find_if_not(text, [](unsigned char ch) { return std::isspace(ch) != 0; }); std::cout << '[' << std::string_view(it, text.end()) << "]\n"; }
Output
The pipeline prints [ranges are lazy], and an all-space input drops to nothing: []. The one-sided version builds a std::string_view from the found iterator to the end, the C++20 iterator-pair constructor: [left only]. In C++23, | std::ranges::to<std::string>() could end the pipeline instead of the iterator constructor; this page compiles as C++20.
4Removing or collapsing inner whitespace
A trim only touches the ends. To remove every space, C++20 has std::erase_if(s, pred) and std::erase(s, ' ') for strings; before C++20 the same job is the erase-remove idiom. To trim and squeeze each inner run of whitespace into a single space, read the words with >>, which skips any run of whitespace, and join them again.
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> int main() { // C++20: std::erase_if removes every matching character in one call std::string phone = " +1 555\t010 9999 "; std::erase_if(phone, [](unsigned char ch) { return std::isspace(ch) != 0; }); std::cout << '[' << phone << "]\n"; // Only the space character: std::erase with a value std::string code = "AB 12 CD"; std::erase(code, ' '); std::cout << '[' << code << "]\n"; // Before C++20: the erase-remove idiom does the same std::string old = "x y z"; old.erase(std::remove(old.begin(), old.end(), ' '), old.end()); std::cout << '[' << old << "]\n"; // Trim AND collapse every inner run of whitespace to one space: // >> skips any run of whitespace, so read words and join them std::string messy = " too many \t spaces\n here "; std::istringstream in(messy); std::string word; std::string result; while (in >> word) { if (!result.empty()) { result += ' '; } result += word; } std::cout << '[' << result << "]\n"; }
Output
erase_if with isspace removes spaces and the tab: [+15550109999]. std::erase(code, ' ') removes only the space character, [AB12CD], and the erase-remove line gives [xyz]. std::remove alone does not shrink the string: it moves the kept characters forward and returns the new end, which is why the erase around it is needed. The word loop turns " too many \t spaces\n here " into [too many spaces here]. The same >> loop is how you split a string into words.
5No-break spaces, zero-width spaces and the BOM
std::isspace and the " \t\n\v\f\r" set see bytes, so they only know the six ASCII whitespace characters. Text pasted from a web page often carries a no-break space (U+00A0, two bytes in UTF-8) or a zero-width space (U+200B), and a file saved with a byte order mark starts with U+FEFF. Neither trim above removes them, and the string still fails an equality check. Since UTF-8 encodes each one as a fixed byte sequence, strip those sequences with starts_with and ends_with.
#include <array> #include <cctype> #include <iostream> #include <string> #include <string_view> // UTF-8 sequences std::isspace never matches: it looks at one byte at a time constexpr std::array<std::string_view, 4> invisible = { " ", // no-break space, 2 bytes "", // zero-width space, 3 bytes " ", // ideographic space, 3 bytes "", // byte order mark, 3 bytes }; // Remove one ASCII space or one invisible sequence from the front bool strip_front(std::string_view& s) { if (!s.empty() && std::isspace(static_cast<unsigned char>(s.front()))) { s.remove_prefix(1); return true; } for (std::string_view w : invisible) { if (s.starts_with(w)) { s.remove_prefix(w.size()); return true; } } return false; } bool strip_back(std::string_view& s) { if (!s.empty() && std::isspace(static_cast<unsigned char>(s.back()))) { s.remove_suffix(1); return true; } for (std::string_view w : invisible) { if (s.ends_with(w)) { s.remove_suffix(w.size()); return true; } } return false; } std::string_view trim_utf8(std::string_view s) { while (strip_front(s)) { } while (strip_back(s)) { } return s; } int main() { // Text pasted from a web page: no-break spaces and a zero-width space std::string pasted = " price: 10 "; // An ASCII-only trim finds nothing to remove at either end std::string_view ws = " \t\n\v\f\r"; std::size_t first = pasted.find_first_not_of(ws); std::size_t last = pasted.find_last_not_of(ws); std::cout << "ASCII trim keeps bytes " << first << " to " << last << " of " << pasted.size() << '\n'; std::cout << '[' << trim_utf8(pasted) << "]\n"; // A file saved with a BOM: the first header is not "name" until it goes std::string header = "name,age"; std::cout << std::boolalpha << header.starts_with("name") << ' ' << trim_utf8(header).starts_with("name") << '\n'; }
Output
The ASCII trim leaves all 17 bytes: ASCII trim keeps bytes 0 to 16 of 17, because the first and last bytes belong to multi-byte sequences. trim_utf8 removes the no-break spaces, the ASCII space and the zero-width space: [price: 10]. The header line prints false true: with its BOM it does not start with name, and after the trim it does. GCC stores \u00A0 in a plain string literal as UTF-8 by default; for other compilers, write the bytes (\xC2\xA0) or use u8 literals. Extend the list with the characters your input actually contains.
6Which should you use?
| Method | Result | Standard | Best for |
|---|---|---|---|
| find_first_not_of / find_last_not_of | View, no copy | C++17 (string_view) | Most code; custom character sets |
| s.erase + std::find_if_not | Edits in place | C++11 | Cleaning a string you own |
| views::drop_while + views::reverse | New string | C++20 | Code already written as range pipelines |
| std::erase_if(s, isspace) | Edits in place | C++20 | Removing every space, inner ones too |
| istringstream >> word, joined | New string | Any | Trimming and collapsing inner runs |
| starts_with / ends_with loop | View, no copy | C++20 | No-break spaces, zero-width spaces, BOM |
Frequently asked questions
Does C++ have a built-in trim function for std::string?
No. Neither std::string nor std::string_view has trim, up to and including C++23, so every codebase writes its own from find_first_not_of and find_last_not_of, or from erase and std::find_if_not. Boost has boost::algorithm::trim and trim_copy if you already use Boost.
Why cast to unsigned char before calling std::isspace?
std::isspace takes an int that must be EOF or a value representable as unsigned char. Where char is signed, bytes 128 to 255 (every byte of a UTF-8 character such as é) arrive as negative numbers, and passing one is undefined behaviour. Declare the lambda parameter as unsigned char, or call std::isspace(static_cast<unsigned char>(c)).
How do I remove the trailing newline or \r from a string in C++?
std::getline already drops the \n, but a line from a Windows file keeps its \r. Remove it with if (!s.empty() && s.back() == '\r') s.pop_back();, or right-trim with s.erase(s.find_last_not_of("\r\n") + 1);, which also empties a string made only of line breaks because npos + 1 is 0.
How do I remove all spaces from a string in C++?
In C++20, std::erase(s, ' ') removes every space character and std::erase_if(s, [](unsigned char c) { return std::isspace(c) != 0; }) removes all whitespace, tabs and newlines included. Before C++20, use the erase-remove idiom: s.erase(std::remove(s.begin(), s.end(), ' '), s.end());.
Should a trim function return std::string or std::string_view?
A std::string_view result costs nothing, which suits parsing, comparing and lookups, but it points into the original, so it must not outlive it: trim(std::string(" x ")) returns a view of a destroyed temporary. Return std::string when callers keep the result, or let them copy with std::string(trim(s)).
Why does my trimmed string still not compare equal?
Usually an invisible character the trim did not count as whitespace: a no-break space (U+00A0) or zero-width space (U+200B) from copied web text, a byte order mark at the start of a file, or a \r from Windows line endings if your character set leaves it out. Print the size or each byte as a number to find it, then add it to the set you trim.