C++ Remove new line from multiline string

shergill picture shergill · Sep 28, 2009 · Viewed 127.7k times · Source

Whats the most efficient way of removing a 'newline' from a std::string?

Answer

luke picture luke · Sep 28, 2009
#include <algorithm>
#include <string>

std::string str;

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

The behavior of std::remove may not quite be what you'd expect. See an explanation of it here.