Replace line breaks in a STL string

烈酒焚心 提交于 2019-12-22 04:04:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!