How can I replace \r\n
in an std::string
?
如何在std :: string中替换\ r \ n?
4 个解决方案
#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.
不要重新发明*,Boost String Algorithms是一个仅限标题的库,我有理由相信它可以在任何地方使用。如果您认为接受的答案代码更好,因为它已经提供,而您不需要查看文档,这里。
#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;
}
#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:
首先使用find()查找“\ r \ n”,然后使用replace()在其中放置其他内容。看看参考文献,它有一些例子:
http://www.cplusplus.com/reference/string/string/find.html
http://www.cplusplus.com/reference/string/string/replace.html
#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.
不要重新发明*,Boost String Algorithms是一个仅限标题的库,我有理由相信它可以在任何地方使用。如果您认为接受的答案代码更好,因为它已经提供,而您不需要查看文档,这里。
#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.
请参阅Boost String Algorithms库。
#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:
首先使用find()查找“\ r \ n”,然后使用replace()在其中放置其他内容。看看参考文献,它有一些例子:
http://www.cplusplus.com/reference/string/string/find.html
http://www.cplusplus.com/reference/string/string/replace.html