Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Strings and I/O

C++ string::replace and erase

Change a std::string in place with replace, erase, insert, clear and pop_back. Includes a replace-all helper, iterator versions and invalidation rules.

replace overwrites a range of a std::string with new text, and the new text may have a different length, so the string grows or shrinks. erase removes a range, and insert adds text at a position. All of them change the string in place and return *this (the iterator forms of erase and insert return iterators).

Notice what is missing: there is no member "replace all occurrences". replace works on a position and a length. To replace every occurrence of a pattern you combine find and replace in a loop, as shown below.

C++
std::string s = "hello world";
s.replace(0, 5, "HELLO");   // "HELLO world"
s.erase(5, 1);              // "HELLOworld"
s.insert(5, ", ");          // "HELLO, world"

Try it

C++ replace, erase and insert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Replace all occurrences

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
basic_string& replace(size_type pos, size_type count, const basic_string& str);
basic_string& replace(size_type pos, size_type count, const char* s);
basic_string& replace(size_type pos, size_type count, size_type count2, char ch);
basic_string& replace(const_iterator first, const_iterator last, const basic_string& str);

basic_string& erase(size_type pos = 0, size_type count = npos);
iterator erase(const_iterator position);
iterator erase(const_iterator first, const_iterator last);

basic_string& insert(size_type pos, const basic_string& str);
iterator insert(const_iterator position, char ch);

void pop_back();
void clear() noexcept;
Name Description
pos Index where the operation starts. Must be <= size() (and < size() for the single-element erase forms).
count Number of existing characters affected; clamped to the end of the string.
str, s, count2, ch The replacement or inserted text.
first, last, position Iterator equivalents of the position arguments.

Returns: *this for index versions; an iterator to the character after the erased range (or to the new element for insert) for iterator versions.

Errors / undefined behavior: std::out_of_range when pos is invalid, std::length_error if the result is too long. pop_back() and erase(const_iterator) on an empty string are undefined.

Usage notes

  • Iterators and references are invalidated by every modifying call that changes size or reallocates. Re-compute positions after each change, or keep working with indexes.
  • Replace-all loops must advance past the replacement (pos += to.size()), otherwise replacing "a" with "aa" never ends.
  • Cost: replacing or erasing in the middle shifts the tail, so each call is O(n). For many edits, build a new string in one pass.
  • Single characters: std::replace swaps one character value for another; std::erase(s, ch) and std::erase_if (C++20) remove characters, see erase-remove.
  • erase(pos) versus erase(it): passing a plain number like 0 is treated as an index; passing s.begin() is the iterator overload that removes one element.
  • Self-references such as s.replace(0, 1, s) are allowed; the standard requires the result to be as if the argument were copied first.
  • Case changes are not part of std::string: use std::transform with std::toupper on unsigned char.