12

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

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
michael
  • 3,250
  • 10
  • 43
  • 58

4 Answers4

31

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;
}
Noam M
  • 3,156
  • 5
  • 26
  • 41
Hippiehunter
  • 967
  • 5
  • 11
  • 2
    or just use standard library functions to avoid the boost dependency: http://stackoverflow.com/questions/1488775/c-remove-new-line-from-multiline-string – Code Abominator Aug 18 '14 at 03:07
16

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 );
}
Noam M
  • 3,156
  • 5
  • 26
  • 41
lsalamon
  • 7,998
  • 6
  • 50
  • 63
  • 1
    Don't run the find twice! Store the position found in the conditional and use it in the body: while (size_type pos = str.find(...)) { str.manipulate(pos,...); }; – dmckee --- ex-moderator kitten Jan 27 '09 at 17:56
  • Hmmm...that still leaves something to be desired. Each iteration of the loop rescans the bit declared safe by the last pass. Define pos outside the loop and make it persistant: size_type pos = 0; while (pos = str.find("..",pos) )... – dmckee --- ex-moderator kitten Jan 27 '09 at 18:24
  • 5
    This is an erasure and not a replacement - the question asked was how to replace "\r\n"; they may have needed to replace it with another character. – SteJ Apr 03 '16 at 23:12
5

See Boost String Algorithms library.

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88
3

First use find() to look for "\r\n", then use replace() to put something else there. Have a look at the reference, it has some examples:

http://www.cplusplus.com/reference/string/string/find.html

http://www.cplusplus.com/reference/string/string/replace.html

Joao da Silva
  • 7,353
  • 2
  • 28
  • 24