Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Remove new line from multiline string

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

like image 400
shergill Avatar asked Sep 28 '09 19:09

shergill


4 Answers

#include <algorithm>
#include <string>

std::string str;

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

The behavior of std::remove may not quite be what you'd expect.

A call to remove is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size.

See an explanation of it here.

like image 165
luke Avatar answered Nov 08 '22 02:11

luke


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);
}
like image 45
Greg Hewgill Avatar answered Nov 08 '22 02:11

Greg Hewgill


You should use the erase-remove idiom, looking for '\n'. This will work for any standard sequence container; not just string.

like image 7
coppro Avatar answered Nov 08 '22 02:11

coppro


Here is one for DOS or Unix new line:

    void chomp( string &s)
    {
            int pos;
            if((pos=s.find('\n')) != string::npos)
                    s.erase(pos);
    }
like image 5
edW Avatar answered Nov 08 '22 01:11

edW