< Previous | Contents | Next >

Using the erase() Member

Function

The erase() member function removes a specified substring from a string object. One way to call the member function is to specify the beginning position and the length of the substring, as I did in this code:


phrase.erase(4, 5);


The previous line removes the five-character substring starting at position 4. Because phrase is "Lame Over!!!", the member function removes the substring Over and, as a result, phrase becomes "Lame!!!".

Another way to call erase() is to supply just the beginning position of the substring. This removes all of the characters starting at that position number to the end of the string object. Thats what I do next:

phrase.erase(4);


This line removes all of the characters of the string object starting at position 4. Since phrase is "Lame!!!", the member function removes the substring !!! and, as a result, phrase becomes "Lame".

Yet another way to call erase() is to supply no arguments, as I did in this code:


phrase.erase();

96 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble


The previous line erases every character in phrase. As a result, phrase becomes the empty string, which is equal to "".