What is string erase in C++?

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 after pos are removed.

1. erase()

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;
}

2. Using erase(pos)

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;
}

3. Using erase(pos, count)

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;
}

4. Using erase(iterator index)

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;
}

5. Using erase(iterator begin, iterator end)

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;
}

Conclusion

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

Copyright ©2024 Educative, Inc. All rights reserved