Removing characters from a string

I want to remove a particular character from a string. Say '.'.
I've tried the following:

void removeDots(std::string &x)
{
std::remove_if(x.begin(),x.end(),[](char c){return (c == '.');});
}

This has the effect of removing the dots but keeping the length of the string the same, so old characters are left over at the end. Is there an extra action to do to x to make it the right size or is there a better way of doing it?
1
2
3
4
5
void removeDots(std::string &x)
{
  auto it = std::remove_if(std::begin(x),std::end(x),[](char c){return (c == '.');});
  x.erase(it, std::end(x));
}


The remove_if is a generic algorithm, it can accept any iterator which match the concepts of forward iterator.But this algorithm don't know how to erase(remove the data from the containers), shrink the size of the containers.Instead of it, this algorithm will removes all elements satisfying specific criteria from the range [first, last) and returns a past-the-end iterator for the new end of the range.

You could use the iterator return from the algorithm to "erase" the data
Thank you stereoMatching for the explanation and thank you both for the code examples. You've both been a great help.
Last edited on
Topic archived. No new replies allowed.