Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Removing characters from string using STL

Tags:

c++

stl

stdstring

I'm having a small brain fart: I'd like to remove all instances of the newline character '\n' in a std::string. I'd prefer to use the STL instead of manual, multi-nested for loops; the only problem is I've forgotten how...

Would for(...) { std::string::remove_if(...); } ; work? Could I need to use std::for_each(...,..., std::string::remove_if(...));? Or would something else be required?

like image 567
Casey Avatar asked Jun 14 '12 03:06

Casey


2 Answers

First idea: the remove/erase idiom:

str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
like image 80
yves Baumes Avatar answered Sep 23 '22 12:09

yves Baumes


If you have Boost.Range it works even shorter:

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

boost::remove_erase(str, '\n');
like image 30
gast128 Avatar answered Sep 26 '22 12:09

gast128