Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace line breaks in a STL string

Tags:

c++

stl

How can I replace \r\n in an std::string?

like image 530
michael Avatar asked Jan 27 '09 16:01

michael


2 Answers

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;
}
like image 148
Hippiehunter Avatar answered Oct 13 '22 17:10

Hippiehunter


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 );
}
like image 31
lsalamon Avatar answered Oct 13 '22 18:10

lsalamon