How to Erase Character from String in C++: Simple Guide
In C++, you can erase a character from a string using the
erase() method by specifying the position of the character to remove. For example, str.erase(pos, 1) removes one character at index pos from the string str.Syntax
The erase() method removes characters from a string. You specify the starting position and the number of characters to erase.
str.erase(pos, len): Removeslencharacters starting at indexpos.posis zero-based, meaning the first character is at position 0.- If
lenis 1, only one character is removed.
cpp
str.erase(pos, 1);
Example
This example shows how to remove the character 'o' from the string "Hello" by erasing the character at position 4.
cpp
#include <iostream> #include <string> int main() { std::string str = "Hello"; // Erase character at position 4 ('o') str.erase(4, 1); std::cout << str << std::endl; return 0; }
Output
Hell
Common Pitfalls
Common mistakes when erasing characters from strings include:
- Using an invalid position that is out of the string's range, which causes undefined behavior or crashes.
- Forgetting that string indices start at 0, so the first character is at position 0.
- Not specifying the length to erase, which defaults to erasing from the position to the end of the string.
Always check the string length before erasing.
cpp
#include <iostream> #include <string> int main() { std::string str = "Hello"; // Wrong: position 10 is out of range // str.erase(10, 1); // This causes error // Correct: erase last character if (!str.empty()) { str.erase(str.size() - 1, 1); } std::cout << str << std::endl; return 0; }
Output
Hell
Quick Reference
| Method | Description | Example |
|---|---|---|
| erase(pos, len) | Removes len characters starting at pos | str.erase(2, 1); removes one char at index 2 |
| erase(iterator) | Removes character at iterator position | str.erase(str.begin() + 2); |
| erase(iterator first, iterator last) | Removes characters in range [first, last) | str.erase(str.begin(), str.begin() + 3); |
Key Takeaways
Use
erase(pos, 1) to remove a single character at position pos.Always ensure the position is within the string length to avoid errors.
String indices start at 0, so count positions carefully.
You can also erase using iterators for more flexibility.
If length is omitted,
erase(pos) removes from pos to the end.