std::string erase() method
- since C++20
- since C++11
- until C++11
// (1) Non const version only
constexpr basic_string& erase( size_type index = 0, size_type count = npos );
// (2) Non const version only
constexpr iterator erase( const_iterator position );
// (3) Non const version only
constexpr iterator erase( const_iterator first, const_iterator last );
// (1) Non const version only
basic_string& erase( size_type index = 0, size_type count = npos );
// (2) Non const version only
iterator erase( const_iterator position );
// (3) Non const version only
iterator erase( const_iterator first, const_iterator last );
// (1) Non const version only
basic_string& erase( size_type index = 0, size_type count = npos );
// (2) Non const version only
iterator erase( iterator position );
// (3) Non const version only
iterator erase( iterator first, iterator last );
Erases specified characters from the string.
- (1) Removes
std::min(count, size() - index)
characters starting atindex
. - (2) Removes the character at
position
. - (3) Removes the characters in the range [ first, last ).
Parameters
index
- first character to removecount
- number of characters to removeposition
- iterator to the character to removefirst
,last
- range of the characters to remove
Return value
- (1)
*this
- (2)
Iterator pointing to the character immediately following the character erased.
end()
if no such character exists. - (3)
Iterator pointing to the character last pointed to before the erase.
end()
if no such character exists.
Complexity
important
This section requires improvement. You can help by editing this doc page.
Exceptions
- (1)
std::out_of_range
ifindex > size()
. - (2-3) (none)
Example
Main.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main()
{
std::string s = "This Is An Example";
std::cout << "1) " << s << '\n';
s.erase(7, 3); // erases " An" using overload (1)
std::cout << "2) " << s << '\n';
s.erase(std::find(s.begin(), s.end(), ' ')); // erases first ' '; overload (2)
std::cout << "3) " << s << '\n';
s.erase(s.find(' ')); // trims from ' ' to the end of the string; overload (1)
std::cout << "4) " << s << '\n';
auto it = std::next(s.begin(), s.find('s')); // obtains iterator to the first 's'
s.erase(it, std::next(it, 2)); // erases "sI"; overload (3)
std::cout << "5) " << s << '\n';
}
Output
1) This Is An Example
2) This Is Example
3) ThisIs Example
4) ThisIs
5) This
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.