C ++在单个遍中替换字符串中的多个字符串 [英] C++ replace multiple strings in a string in a single pass
问题描述
给定以下字符串,Hi〜+和^ *。^ *仍在飞来飞去〜+?
我想用Bobby替换所有出现的〜+
和^ *
和Danny,所以字符串变成:
I want to replace all occurrences of "~+"
and "^*"
with "Bobby" and "Danny", so the string becomes:
你好鲍比和丹尼,丹尼依然在鲍比飞吗?
我不想调用Boost替换函数两次来替换两个不同值的出现。
I would prefer not to have to call Boost replace function twice to replace the occurrences of the two different values.
推荐答案
我设法使用Boost.Iostreams实现所需的替换函数。具体来说,我使用的方法是使用正则表达式匹配要替换的过滤流。我不知道在gigabyte大小的文件的性能。你需要测试它当然。无论如何,这里是代码:
I managed to implement the required replacement function using Boost.Iostreams. Specifically, the method I used was a filtering stream using regular expression to match what to replace. I am not sure about the performance on gigabyte sized files. You will need to test it of course. Anyway, here's the code:
#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();
}
上面的图片Hi Bobby和Danny Danny仍然在Bobby附近飞行?
运行时,就像预期的那样。
The above prints "Hi Bobby and Danny. Is Danny still flying around Bobby?"
when run, just like expected.
如果你决定测量它。
丹尼尔
编辑:我只是意识到 regex_filter
需要将整个字符序列读入内存,这对于千兆字节大小的输入来说是无用的。哦,好...
I just realized that regex_filter
needs to read the entire character sequence into memory, making it pretty useless for gigabyte-sized inputs. Oh well...
这篇关于C ++在单个遍中替换字符串中的多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!