Replace line breaks in a STL string

Use this :

while ( str.find ("\r\n") != string::npos )
{
    str.erase ( str.find ("\r\n"), 2 );
}

more efficient form is :

string::size_type pos = 0; // Must initialize
while ( ( pos = str.find ("\r\n",pos) ) != string::npos )
{
    str.erase ( pos, 2 );
}

See Boost String Algorithms library.


don't reinvent the wheel, Boost String Algorithms is a header only library and I'm reasonably certain that it works everywhere. If you think the accepted answer code is better because its been provided and you don't need to look in docs, here.

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>

int main()
{
    std::string str1 = "\r\nsomksdfkmsdf\r\nslkdmsldkslfdkm\r\n";
    boost::replace_all(str1, "\r\n", "Jane");
    std::cout<<str1;
}

Tags:

C++

Stl