C++在一次传递中替换字符串中的多个字符串

Joh*_*son 17 c++ string boost str-replace

给出以下字符串, "Hi ~+ and ^*. Is ^* still flying around ~+?"

我想替换所有出现"~+",并"^*"以"波比"和"丹尼",因此字符串变成:

"Hi Bobby and Danny. Is Danny still flying around Bobby?"

我宁愿不必两次调用Boost替换函数来替换两个不同值的出现.

Dan*_*röm 7

我设法使用Boost.Iostreams实现了所需的替换功能.具体来说,我使用的方法是使用正则表达式匹配要替换的过滤流.我不确定gigabyte文件的性能.你当然需要测试它.无论如何,这是代码:

#include <boost/regex.hpp>
#include <boost/iostreams/filter/regex.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <iostream>

int main()
{
   using namespace boost::iostreams;

   regex_filter filter1(boost::regex("~\\+"), "Bobby");
   regex_filter filter2(boost::regex("\\^\\*"), "Danny");

   filtering_ostream out;
   out.push(filter1);
   out.push(filter2);
   out.push(std::cout);

   out << "Hi ~+ and ^*. Is ^* still flying around ~+?" << std::endl;

   // for file conversion, use this line instead:
   //out << std::cin.rdbuf();
}
Run Code Online (Sandbox Code Playgroud)

"Hi Bobby and Danny. Is Danny still flying around Bobby?"运行时上面打印,就像预期一样.

如果你决定测量它,那么看到性能结果会很有趣.

丹尼尔

编辑:我刚刚意识到regex_filter需要将整个字符序列读入内存,这对于千兆字节大小的输入来说非常无用.那好吧...


Gre*_*hen 0

Boost string_algo 确实有一个replace_all 函数。你可以用那个。