In C++, the erase
function is a method available for std::string
objects in the Standard Template Library (STL). It removes characters from a string. The erase
function has several overloaded versions, but the most common form takes two parameters:
string& erase(size_t pos, size_t count = npos);
pos:
Specifies the position of the first character to be removed
count:
The number of characters to remove.
Note: If
count
is not specified, or if it is greater than the remaining characters in the string starting from the first character to be removed, all characters afterpos
are removed.
erase()
will erase the complete string. Here is an executable example:
#include <iostream>#include <string>using namespace std;int main() {string str = "Hello World";cout << "Initially: " << str << endl;str.erase();cout << "After using erase(): " << str;return 0;}
erase(pos)
will delete all the characters after the specified position. Take a look at the code below:
#include <iostream>#include <string>using namespace std;int main() {string str = "Hello World";cout << "Initially: " << str << endl;str.erase(2);cout << "After using erase(2): " << str;return 0;}
erase(pos, count)
will delete the specified number (length) of characters after the specified position. Take a look at the code below:
#include <iostream>#include <string>using namespace std;int main() {string str = "Hello World";cout << "Initially: " << str << endl;str.erase(2, 4);cout << "After using erase(2, 4): " << str;return 0;}
erase(iterator index)
will delete the specific character at the specified iterator position. Here is an executable example for you to try:
#include <iostream>#include <string>using namespace std;int main() {string str = "Hello World";cout << "Initially: " << str << endl;str.erase(str.begin() + 2);cout << "After using str.erase(str.begin() + 2): " << str;return 0;}
erase(iterator begin, iterator end)
will delete specific characters, starting from the iterator begin
position before the iterator end
position. It does not delete the character at iterator end
. Take a look at the following code:
#include <iostream>#include <string>using namespace std;int main() {string str = "Hello World";cout << "Initially: " << str << endl;str.erase(str.begin() + 2, str.begin() + 5);cout << "After using erase(str.begin() + 2, str.begin() + 5) " << str;return 0;}
The erase
function in C++'s std::string
removes characters based on certain parameters. It offers flexibility by allowing deletion of characters from a specific position or range, making it a powerful tool for string manipulation tasks.
Free Resources