From aldeid
Jump to navigation Jump to search


string& erase (size_t pos = 0, size_t len = npos);  // sequence (1)
iterator erase (iterator p);                        // character (2)
iterator erase (iterator first, iterator last);     // range (3)


Erase characters from string

Erases part of the string, reducing its length:

  1. sequence
    Erases the portion of the string value that begins at the character position pos and spans len characters (or until the end of the string, if either the content is too short or if len is string::npos.
    Notice that the default argument erases all characters in the string (like member function clear).
  2. character
    Erases the character pointed by p.
  3. range
    Erases the sequence of characters in the range [first,last).


Position of the first character to be erased.
If this is greater than the string length, it throws out_of_range.
Note: The first character in str is denoted by a value of 0 (not 1).
Number of characters to erase (if the string is shorter, as many characters as possible are erased).
A value of string::npos indicates all characters until the end of the string.
Iterator to the character to be removed.
first, last
Iterators specifying a range within the string] to be removed: [first,last). i.e., the range includes all the characters between first and last, including the character pointed by first but not the one pointed by last.
  • size_t is an unsigned integral type (the same as member type string::size_type).
  • Member types iterator and const_iterator are random access iterator types that point to characters of the string.

Return value

The sequence version (1) returns *this.

The others return an iterator referring to the character that now occupies the position of the first character erased, or string::end if no such character exists.

Member type iterator is a random access iterator type that points to characters of the string.


Source Output
#include <iostream>
#include <string>
using namespace std;

int main()
  string str("Hello world, this is a test");
  cout << "Before: " << str << endl;
  str.erase(5, 6);
  cout << "After:  " << str << endl;
  return 0;
Before: Hello world, this is a test
After:  Hello, this is a test