The function erases a part of the string content, shortening the length of the string. The characters affected depend on the member function version used:
Return value : erase() returns *this.
- Syntax 1: Erases all characters in a string
string& string ::erase ()
Before erase() : Hello World! After erase() :
2. Syntax 2: Erases all characters after position ‘pos’
string& string ::erase (size_type pos) - Throw out_of_range if idx > size().
Before erase(idx) : Hello World! After erase(idx) : H
3. Syntax 3: Erases at most, len characters of *this, starting at index idx.
string& string ::erase (size_type idx, size_type len ) - If len is missing, all remaining characters are removed. - Throw out_of_range if idx > size().
Before erase : Hello World! After erase : H World!
4. Syntax 4: Erase the single character at iterator position pos.
string& string ::erase (iterator pos) - Return the first character after the last character removed - If no such character is remaining then, returns string::end() i.e. position after the last character.
Before erase : Hello World! After erase : Hell World!
5. Syntax 5: Erase characters from iterator pos. to another iterator pos.
string& string ::erase (iterator beg, iterator end ) - Erases all characters of the range [ beg, end) - Returns end i.e. the first character after the last character removed. - If no such character is remaining then, returns string::end() i.e. position after the last character
Before erase : Hello World! After erase : World!
Related Article : std::string::clear
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Draw an ellipse divided by straight line into two colored part in C++ Graphics
- What happens if we mix new and free in C++?
- VS Code | Build, Run and Debug in C++
- VS Code | Compile and Run in C++
- Difference between sizeof(int *) and sizeof(int) in C/C++
- Runtime and Compile-time constants in C++
- Efficient ways to compare a variable with multiple values
- Overloading the Comma Operator
- Difference between C++ and PHP
- Custom Jumble Word Game
- Comparator Class in C++ with Examples
- Complete Guide to Install C++17 in Windows
- Features of C++
- Draw a triangle in C++ graphics
- Implementation of lower_bound() and upper_bound() in List of Pairs in C++
Improved By : abhishekrbg