![]() |
VOOZH | about |
The string::erase() function in C++ is a built-in function of the string class that is used to remove characters from a string. It can erase a single character, multiple characters, a range of characters, or even clear the entire string.
Hello World!
The string erase() function provides 5 different overloads for different purposes:
// Erases whole string
s.erase();// Erases all characters after idx
s.erase(idx);// Erases k characters after idx
s.erase(idx, k);// Erases character at itr
s.erase(itr);// Erases characters in range [first, last)
s.erase(first, last);
string erase() function can be used for erasing a single character from the specific position in the string.
Syntax:
s.erase(itr);
Parameters
Return Value
Hell World!
We can also erase a range of characters from the string using string erase() function.
Syntax:
s.erase(first, last);
Parameters
Return Value
World!
The below version erases all the characters after the given index, but we can also limit the number of characters to be deleted using string::erase.
Syntax:
s.erase(idx, k);
Parameters
Return Value
World!
string erase() function can also be instructed to erase the characters after some given position.
Syntax:
s.erase(idx);
Parameters
Return Value
Hello
The string erase() function is able to delete all the characters of the string effectively clearing it. The length of the string will be reduced to 0.
Syntax:
s.erase();
Parameter
Return Value
Output
(no output)
The string clear() is a function used to erase the contents of the string, but it is a lot different from string erase(). Below is the table that lists the major differences between string erase() and string clear().
| Aspect | string::erase() | string::clear() |
|---|---|---|
| Purpose | Removes specific characters or a range of characters. | Removes all characters from the string. |
| Syntax | erase(position); erase(first, last); | clear(); |
| Parameters | - Position of a single character - Range of characters (two iterators) | None |
| Returns | Iterator pointing to the position after the removed range | None |
| Time Complexity | - Single character: O(m), where m is the number of characters after the position. - Range: O(m - k), where k is the size of the range. | O(1), where n is the number of characters in the string. |
| Space Complexity | O(1), as it modifies the string in place. | O(1), as it clears the string in place. |