问题
How can I replace \r\n
in an std::string
?
回答1:
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 );
}
回答2:
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;
}
回答3:
See Boost String Algorithms library.
回答4:
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
来源:https://stackoverflow.com/questions/484213/replace-line-breaks-in-a-stl-string