c + +替换字符串多个字符串在一个单一的通 [英] C++ replace multiple strings in a string in a single pass

查看:89
本文介绍了c + +替换字符串多个字符串在一个单一的通的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨〜+和^ *。是^ *仍然甚嚣尘上〜+?

我想要替换所有出现的+^ *与巴比和丹尼,因此字符串变成:

I want to replace all occurrences of "~+" and "^*" with "Bobby" and "Danny", so the string becomes:

Bobby和丹尼。丹尼仍然到处飞鲍比?

我想preFER不要有叫加速替换功能两次更换两个不同的值的出现。

I would prefer not to have to call Boost replace function twice to replace the occurrences of the two different values.

推荐答案

我设法实现使用了Boost.Iostreams所需要的替换功能。具体来说,我采用的方法是使用常规的前pression以匹配更换过滤流。我不知道技嘉大小的文件的性能。您将需要测试,当然它。总之,这里的code:

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();
}

以上版画Bobby和丹尼。丹尼还在身边鲍比飞?运行时,就像预期的。

这将看到演出的效果,如果你决定来衡量它很有趣。

It would be interesting to see the performance results, if you decide to measure it.

丹尼尔

编辑:我刚刚意识到 regex_filter 需要读取整个字符序列到内存中,使之成为pretty无用千兆字节大小的输入。哦...

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆