Formatting strings in C++
Sometimes you may want to filter a string and remove some characters that appear on that string.
the algorithm library is good for doing just things like that.
In this example I create a string called text with the initial value specified in the quotes.
std::string text("ex-ample-/");
the char array filterChars is used to specify the characters we wish to remove.
char filterChars[] = "-/";std::remove iterates over the text string from the first character (including) to the last characters (not including) and removes the character specified in filterChars. We also want to remove the last character if it is in our filter and we will see what to do in order to achieve that later. The result of std::remove is in iterator to the element that follows the last element not removed.
for (unsigned int i = 0; i < strlen(filterChars); ++i)
{
std::remove(text.begin(), text.end(), filterChars[i]);
}
The result is that "ex-ample-/" turns to "example/-/"
This is because remove traverses from the beginning to the end only taking characters that is not in the filter. and it keeps the last '/' character.
To solve the problem of std::remove not working on the last character we give the result iterator to the erase function.
The erase function will erase all characters in the range between remove result and the actual end of our string, in our case it is the last two characters "-/".
for (unsigned int i = 0; i < strlen(filterChars); ++i)
{
text.erase(std::remove(text.begin(), text.end(), filterChars[i]), text.end());
}
The needed libraries for this code are:
#include <algorithm> #include <string>
The result of running this code is:
text now contains "example"