C ++ Removing characters from a string using STL

I have a little brain fart: I would like to delete all instances of the newline character '\n'in std::string. I would prefer to use STL instead of manual, multi-user for loops; the only problem is I forgot how ...

Will it for(...) { std::string::remove_if(...); } ;work? Can i use std::for_each(...,..., std::string::remove_if(...));? Or will you need something else?

+5
source share
2 answers

First idea: idiom remove / erase:

str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
+19
source

If you have Boost.Range, it works even shorter:

#include <boost\range\algorithm_ext\erase.hpp>

boost::remove_erase(str, '\n');
+3
source

All Articles