How can I replace \r\n
in an std::string
?
Asked
Active
Viewed 2.8k times
12

newfurniturey
- 37,556
- 9
- 94
- 102

michael
- 3,250
- 10
- 43
- 58
-
2Um. What do you want to replace them with? And, maybe a little context would help, no? – dmckee --- ex-moderator kitten Jan 27 '09 at 17:03
-
As @dmckee---ex-moderatorkitten says: the code can be a lot simpler, if you only intend to replace it with a string of length less than or equal to the original. – user2023370 Feb 11 '23 at 14:48
4 Answers
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
-
2or 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 );
}
-
1Don'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
-
5This 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
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
-
Here's an answer that contains a code example: https://stackoverflow.com/a/3418285/1279291 – andreasdr May 14 '19 at 06:12