string
To delete all a specific character from it in C++ , you can use the following code
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
where, remove
from <algorithm>
, its signature is
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);
Function: In the container, delete [first, last)
all values between which are equal to val
the value.
Delete method: Overwrite a val
value that is equal to the next val
value that is not equal to.
Return value: an iterator (denoted as newEnd
), which points to the element next to the last undeleted element, which is equivalent to the container new end
.
Therefore, remove
after , [first, newEnd)
the elements in the container are all the elements that have not been deleted, and [newEnd, end)
the elements in between are useless.
In this way, the elements in between str.erase(newEnd, str.end())
can be cleared by running again.[newEnd, end)