how can i replace "\r\n" in an std::string
+2
A:
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
João da Silva
2009-01-27 17:18:03
+7
A:
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 );
}
lsalamon
2009-01-27 17:36:46
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
2009-01-27 17:56:29
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
2009-01-27 18:24:32
+5
A:
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;
}
Hippiehunter
2009-01-27 20:00:31
A:
Depending upon your company's policies, boost might not be available. Visual Studio and most Linux distros come with Standard Template Library, so an STL option is equally valid to the boost option above.
Bill Perkins
2009-01-27 20:54:05
If boost(headers only) isn't available you should rage until it is. If it stays unavailable, its probably not a place you want to work at imo(barring xyz crazy platform with zyx terrible C++ compiler)
Hippiehunter
2009-01-27 21:29:49