erase

C++ Reference

erase
Syntax:
  #include <string>
  iterator erase( iterator loc );
  iterator erase( iterator start, iterator end );
  string& erase( size_type index = 0, size_type num = npos );

The erase() function either:

  • removes the character pointed to by loc, returning an iterator to the next character,
  • removes the characters between start and end (including the one at start but not the one at end), returning an iterator to the character after the last character removed,
  • or removes num characters from the current string, starting at index, and returns *this.

The parameters index and num have default values, which means that erase() can be called with just index to erase all characters after index or with no arguments to erase all characters.

For example:

   string s("So, you like donuts, eh? Well, have all the donuts in the world!");
   cout << "The original string is '" << s << "'" << endl;          

   s.erase( 50, 14 );
   cout << "Now the string is '" << s << "'" << endl;
   s.erase( 24 );
   cout << "Now the string is '" << s << "'" << endl;
   s.erase();
   cout << "Now the string is '" << s << "'" << endl;               

will display

   The original string is 'So, you like donuts, eh? Well, have all the donuts in the world!'
   Now the string is 'So, you like donuts, eh? Well, have all the donuts'
   Now the string is 'So, you like donuts, eh?'
   Now the string is ''         

erase() runs in linear time.

Related topics: