The erase() member function is the primary way to remove characters from a std::string in C++. It can delete a single character, a range of characters, or everything after a given position, and it modifies the string in place.
Background: Why erase() Exists
C++ strings are dynamic arrays of characters, and unlike C-style char* arrays, they manage their own memory. Removing characters from a C-style array requires manual shifting and reallocation, which is error-prone. The std::string class provides erase() to handle this safely and efficiently. It is part of the Standard Template Library (STL) and has been available since C++98, with no major changes in later standards (C++11, C++14, C++17, C++20). The function is overloaded to accept different argument types, giving you flexibility in what you remove.
How erase() Works: Three Overloads
There are three common ways to call erase(). Each modifies the string in place and returns a reference to the string itself, allowing chaining (e.g., s.erase(0, 2).erase(3)).
- Erase by position and count:
s.erase(pos, count)removescountcharacters starting at indexpos. Ifcountis omitted, it removes fromposto the end. Example:std::string s = "Hello World"; s.erase(5, 6);results in"Hello". - Erase a single character by iterator:
s.erase(iterator)removes the character pointed to by the iterator. Example:s.erase(s.begin() + 1)removes the second character. - Erase a range by iterators:
s.erase(first, last)removes all characters from the iteratorfirstup to (but not including)last. Example:s.erase(s.begin() + 2, s.begin() + 5)removes characters at indices 2, 3, and 4.
All overloads return a reference to the string, so you can use them in expressions. The time complexity is O(n) where n is the number of characters after the erased portion, because the remaining characters are shifted left to fill the gap.
How to Choose the Right Overload
Your choice depends on what you know about the string at the point of removal:
- If you know the index and the number of characters to remove, use the
(pos, count)overload. This is the most straightforward and works well when you have a position from functions likefind(). - If you are iterating through the string and need to remove the current character, use the iterator overload. Be careful: after erasing, the iterator is invalidated, so you must reassign it to the return value of
erase()if you want to continue iterating. - If you want to remove a contiguous block that you have iterators for (e.g., from
find()results), use the range overload. This is efficient because it avoids multiple single-character shifts.
For most everyday tasks, the (pos, count) overload is the easiest to read and maintain. Use iterators only when you are already working with them, such as inside a loop that uses begin() and end().
Common Problems and Pitfalls
Several mistakes trip up developers new to erase():
- Out-of-range position: If
posis greater than the string length, the behavior is undefined (it may crash or corrupt memory). Always check thatpos < s.size()before calling. - Iterator invalidation: After an
erase(), all iterators, pointers, and references to the erased characters and those after them are invalidated. If you keep an iterator to the middle of the string and then erase, using that iterator later is undefined behavior. - Erasing in a loop: If you loop through a string and erase characters one by one, the indices shift. The classic pattern is to iterate backwards or use
std::remove_ifinstead. - Confusing erase() with clear():
clear()removes all characters (equivalent toerase(0)), but it does not release the underlying capacity.erase()with no arguments is not valid; you must specify at least a position.
Alternatives to erase()
Sometimes erase() is not the best tool. For removing all occurrences of a specific character, consider the erase-remove idiom:
std::string s = "a.b.c.d";
s.erase(std::remove(s.begin(), s.end(), '.'), s.end());
// s becomes "abcd"
This uses std::remove from <algorithm> to shift non-matching characters to the front, then erase() removes the tail. It is O(n) and avoids multiple shifts. For conditional removal, use std::remove_if with a lambda. For extracting a substring without modifying the original, use substr() instead of erasing. For clearing the string entirely, clear() is more idiomatic than erase(0).
Performance and Memory Considerations
erase() does not reduce the string’s capacity (the allocated memory). If you remove many characters, the string still holds the same capacity, which can waste memory if you keep the string around. To shrink the capacity, you can call s.shrink_to_fit() (C++11) or swap with an empty string: std::string(s).swap(s). The time cost of erase() is proportional to the number of characters after the erased section, because they are moved. For a string of length n, erasing from the middle is O(n), while erasing from the end is O(1) (no shifting needed). If you need to remove many characters scattered throughout, the erase-remove idiom is usually faster because it does a single pass.
Safety and Best Practices
To avoid undefined behavior, always validate positions before erasing:
- Use
s.size()to check bounds:if (pos < s.size()) s.erase(pos); - When using iterators, never assume they are still valid after the string is modified. Re-obtain them from
begin()or use the return value oferase(). - In loops that erase while iterating, use the following pattern to stay safe:
for (auto it = s.begin(); it != s.end(); ) {
if (*it == 'x') it = s.erase(it); // erase returns next valid iterator
else ++it;
}
This works because the iterator overload returns an iterator to the element after the erased one. For C++11 and later, you can also use a range-based loop with std::remove_if to avoid manual iterator management.
Frequently Asked Questions
Does erase() free memory?
No. erase() only removes characters; it does not release the allocated capacity. The string’s capacity remains unchanged. If you need to release memory, call shrink_to_fit() or swap with an empty string.
Can I erase characters from the end using erase()?
Yes. s.erase(s.size() - 1) removes the last character, or s.erase(s.size() - n) removes the last n characters. Alternatively, use s.pop_back() to remove a single last character, which is more readable.
What is the difference between erase() and clear()?
clear() removes all characters from the string, making it empty. erase() removes a specified portion. clear() is equivalent to erase(0), but it is clearer in intent and does not require a position argument.
Why does erase() return a reference to the string?
Returning a reference allows chaining, such as s.erase(0, 2).erase(3). It also matches the convention of other mutating string methods like append() and insert(), which also return references for chaining.
Can I use erase() on a const string?
No. erase() modifies the string, so it can only be called on non-const std::string objects. If you have a const string, you need to copy it first or use substr() to get a modified version.
What happens if I pass a count larger than the remaining characters?
If pos is valid but count extends beyond the end, erase() removes only the characters from pos to the end. It does not throw an exception; it simply stops at the end. For example, std::string s = "abc"; s.erase(1, 10); results in "a".
Related
- Next Tab Shortcut: Windows, Mac & Browser Keys
- Computer Data Entry Operator Resume: Full Guide
- Changing Windows Shortcut: How to Remap Keys
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel TEXT Function Format Codes ExplainedExcel TEXT format codes are patterns you pass to the TEXT function to turn a number, date, time,…
- Merge the Contents of Two Cells in Excel with a FormulaTo combine the contents of two Excel cells without losing either value, enter a formula in a third…
- Insert a Horizontal Page Break in Excel the Right WayTo insert a horizontal page break in Excel for Microsoft 365 on Windows, select the row directly below…
- Split a Cell in Excel: Text to Columns, Formulas, and MoreYes. In Microsoft Excel, select the cells and choose Data > Text to Columns to split their contents…
- Max Value Between Two Dates in Excel: Formula GuideTo find the largest value recorded between two dates in Excel, use =MAXIFS(C2:C100,A2:A100,">="&E2,A2:A100,"<="&F2). This assumes dates are in…
- Excel Sort a List by Another List: Reliable MethodsTo sort Excel rows into the order of a second list, use SORTBY with XMATCH, or add a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.