C++ 替换 STL 字符串中的换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/484213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace line breaks in a STL string
提问by michael
How can I replace \r\n
in an std::string
?
我怎样才能\r\n
在一个中替换std::string
?
回答by Hippiehunter
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;
}
回答by lsalamon
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 );
}
回答by Nemanja Trifunovic
See Boost String Algorithmslibrary.
请参阅提升字符串算法库。
回答by Joao da Silva
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/find.html
http://www.cplusplus.com/reference/string/string/replace.html
http://www.cplusplus.com/reference/string/string/replace.html