Removing characters from a string

Nov 1, 2013 at 3:13pm
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?
Nov 1, 2013 at 3:56pm
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
Nov 1, 2013 at 3:59pm
Nov 4, 2013 at 8:56am
Thank you stereoMatching for the explanation and thank you both for the code examples. You've both been a great help.
Last edited on Nov 4, 2013 at 8:58am
Topic archived. No new replies allowed.