C++ String Erase: How std::string::erase Works

How-to basics · Updated November 22, 2026

In C++, erase characters from a string with one of the std::string::erase overloads: use a position and count, an iterator, or an iterator range. For example, s.erase(2, 3) removes up to three characters starting at index 2; the string closes the gap and becomes shorter.

What std::string::erase Does

std::string::erase removes part or all of a string’s stored character sequence. It changes the original string rather than creating a modified copy, and returns a reference to that string for the position-and-count overload or an iterator for the iterator overloads. The string’s size decreases by the number of characters removed.

For example, if s contains "strawberry", then s.erase(2, 3) removes the three characters beginning at index 2: "raw". The result is "stberry". C++ string positions are zero-based, so index 0 refers to the first character.

Erasing does not leave a blank gap in the string. Characters following the removed section are shifted left, and the string maintains its own length and terminating null character. You do not need to add a null terminator or manually resize the string after calling erase.

The Three Member-Function Overloads

The standard string class provides three commonly used forms. The first takes a starting position and an optional count; the other two use iterators to identify a character or range:

  • s.erase(pos, count) removes up to count characters beginning at position pos. If count is omitted, it defaults to std::string::npos, meaning the removal continues to the end.
  • s.erase(position) removes the single character identified by the iterator and returns an iterator to the character that follows it, or s.end() if the erased character was last.
  • s.erase(first, last) removes the half-open range from first up to, but not including, last. It returns an iterator to the element that follows the erased range, or the new end.

The position overload is often easiest when the location is already known as a number. Iterator overloads are useful when a search or traversal has already produced iterators. The range form also makes it possible to erase everything between two known points without calculating a character count yourself.

Examples by Position and Count

Here is a complete example of removing a fixed section. It includes the needed header and prints the resulting string:

#include <iostream>
#include <string>

int main() {
    std::string word = "strawberry";
    word.erase(2, 3);
    std::cout << word << '\n'; // stberry
}

To remove everything from a position to the end, omit the count. To clear the entire string, call clear() or erase from position zero:

std::string path = "folder/old-name.txt";
path.erase(7);                 // folder

std::string message = "Remove this text";
message.erase(0);              // empty string
// Equivalent for this purpose: message.clear();

There are useful boundary cases. Erasing zero characters changes nothing. A count larger than the number of remaining characters is effectively limited to the available suffix, so s.erase(3, 100) removes from index 3 through the end if that index is valid. A position equal to s.size() is valid and removes nothing; a position greater than s.size() is not valid and causes std::out_of_range.

Examples with Iterators

Iterators let you erase a character found by an algorithm or by a loop. For instance, this removes the first comma if one exists:

std::string csv = "red,green,blue";
auto comma = csv.find(',');
if (comma != std::string::npos) {
    csv.erase(comma, 1);
}

find returns a numeric position, not an iterator, so this example uses the position-and-count overload. For an iterator-based version, convert a valid position with begin() + position. Always check for std::string::npos first: adding that sentinel to an iterator is invalid.

Iterator ranges are especially clear when the endpoints are already available. For example, to remove the first three characters, use s.erase(s.begin(), s.begin() + 3), provided the string has at least three characters. The end iterator is permitted as the second endpoint, making s.erase(s.begin(), s.end()) another way to empty a string. Use clear() when that is the intent, since it communicates the purpose directly.

Removing Matching Characters

A common question is how to remove every occurrence of a character, rather than just one occurrence or one continuous range. Before C++20, the standard approach for a string is the erase-remove idiom, which uses std::remove from <algorithm>:

#include <algorithm>
#include <string>

std::string text = "banana";
text.erase(std::remove(text.begin(), text.end(), 'a'), text.end());
// text is "bnn"

std::remove does not itself shorten the string. It rearranges the elements that should remain toward the beginning and returns an iterator marking the new logical end. The call to erase then deletes the leftover tail. This two-part behavior explains why calling std::remove alone does not remove characters from a container.

Since C++20, the non-member std::erase provides a shorter option for removing all matching values from a string:

#include <string>

std::string text = "banana";
std::erase(text, 'a');
// text is "bnn"

For a condition rather than one exact value, C++20 also provides std::erase_if. For example, std::erase_if(text, [](char ch) { return ch == 'a' || ch == 'e'; }); removes lowercase a and e. These non-member functions are part of the standard library interface declared by <string>; use the erase-remove idiom when compiling in an older language mode.

Erasing While Looping

Removing characters during a loop is a frequent source of bugs. After an erase, the elements after the erased character move left, and iterators at or after the erased location are invalidated. Incrementing an old iterator or retaining an old index without accounting for the removal can skip a character or use an invalid iterator.

When using an iterator loop, assign the returned iterator back to the loop variable and increment only when no erase occurs:

std::string text = "mississippi";
for (auto it = text.begin(); it != text.end(); ) {
    if (*it == 's') {
        it = text.erase(it);
    } else {
        ++it;
    }
}

This removes each s without skipping the character shifted into its place. For simple removal by value, std::erase in C++20 or the erase-remove idiom is usually shorter and less error-prone. If using an index-based loop, iterating backward can avoid the index-shift problem, but the loop bounds must be written carefully to avoid unsigned underflow with std::string::size_type.

Bounds, Return Values, and Iterator Safety

The position overload checks that pos does not exceed the string’s size. If it does, it throws std::out_of_range. The count may extend beyond the end without causing that error; it is limited to the characters available after the starting position. This distinction is useful when removing a suffix whose expected length may be longer than the actual suffix.

For the single-iterator overload, the iterator must refer to an actual character, not end(). Passing end() as the character to erase is invalid. For the range overload, both iterators must form a valid range belonging to the same string; an empty range, such as s.erase(it, it), removes nothing.

After an erase, treat iterators, references, and pointers to characters at or after the erased position as invalid. The returned iterator is the safe way to continue an iterator-based traversal. Also reconsider any saved numeric positions: positions before the erased section remain unchanged, while positions after it refer to different characters because the string has shifted.

Performance and Character Encoding

Erasing a character or range near the beginning can require moving many following characters. Removing a suffix requires no shift of later characters, while removing an interior section generally requires moving the remaining suffix. Thus, repeatedly erasing one character at a time from the front can do substantially more work than making one pass and removing a group of matches together. Exact implementation details vary, but the amount of trailing text is an important practical factor.

One other detail matters when strings contain non-ASCII text: std::string stores char code units, not abstract user-perceived characters. With UTF-8, a visible symbol may occupy multiple bytes, and an accented letter or emoji can use more than one code unit. Erasing one byte by position can split a multi-byte UTF-8 sequence and leave invalid text. If the goal is to remove Unicode characters safely, use a Unicode-aware library or decode text into code points and handle grapheme clusters as required. The ordinary string erase function does not perform Unicode character-boundary checks.

Choosing the Right Erase Method

Choose an overload based on the information your code already has, and on whether the operation removes one match or many:

  • Use erase(pos, count) for a known numeric location, such as deleting a file extension or a fixed prefix.
  • Use erase(it) when an iterator identifies one character, and use erase(first, last) when both range boundaries are known.
  • Use std::erase(s, value) in C++20 or later to remove all occurrences of one character or value.
  • Use std::erase_if in C++20 or later to remove characters meeting a predicate; use erase-remove for earlier standards.
  • Use clear() when the actual goal is to make the string empty.

Prefer the clearest expression over manually reproducing a removal algorithm. In particular, do not repeatedly call erase from the beginning just to filter characters: a single erase-remove pass or the C++20 convenience function states the intent more directly and avoids repeated shifting.

Frequently Asked Questions

How do I erase a character at a specific index in a C++ string?
Use s.erase(index, 1) when index is less than s.size(). The position is zero-based. If you already have an iterator to the character, use s.erase(it).

How do I erase a substring from a string?
Use s.erase(start, length) to remove a substring by starting position and length. Alternatively, use s.erase(first, last) with a valid iterator range; the second iterator marks the first character that stays in the string.

Does erase remove all occurrences?
No. The member call s.erase(pos, count) removes one specified range. To remove every occurrence of a value, use std::erase(s, value) in C++20 or later, or use the erase-remove idiom in older standards.

What happens if the erase position is out of range?
If the position is greater than s.size(), the position-and-count overload throws std::out_of_range. A position equal to the size is valid and removes nothing. An oversized count is clipped to the available characters.

Can I use erase with a C-style string?
No. A C-style character array does not have the std::string::erase member function. Store the text in a std::string, or use appropriate array and length-handling code if the program must work with a character array.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.