C++ Remove new line from multiline string


Question

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

1
49
9/28/2009 7:00:58 PM

Accepted Answer

#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.

104
9/28/2009 7:09:42 PM

If the newline is expected to be at the end of the string, then:

if (!s.empty() && s[s.length()-1] == '\n') {
    s.erase(s.length()-1);
}

If the string can contain many newlines anywhere in the string:

std::string::size_type i = 0;
while (i < s.length()) {
    i = s.find('\n', i);
    if (i == std::string:npos) {
        break;
    }
    s.erase(i);
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon