Remove Characters from a C++ String Using erase()
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
std::string::erase() removes characters directly from a string and has three main overloads. erase(pos, count) deletes up to count characters starting at index pos. erase(first, last) deletes the iterator range [first, last). erase(pos) deletes from pos to the end. All examples print the modified string to standard output.
To remove every occurrence of a specific character, combine std::remove with erase. This is the erase-remove idiom: std::remove shifts kept characters forward and returns a new logical end, then erase deletes the leftover tail. Use std::remove_if with a predicate or lambda to remove characters matching a custom rule, such as vowels.
Time complexity is O(n) per erase operation in the worst case because trailing characters may need to shift. The erase-remove idiom is also O(n) overall, which is better than repeatedly calling erase() in a loop for many removals. Extra space usage is O(1). Always ensure positions and iterator ranges are valid; otherwise the behavior is undefined. The program below is standard C++ and demonstrates each overload plus both removal idioms.