替换字符串中的多对字符 [英] Replace multiple pair of characters in string

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

问题描述

我想用'b'替换所有出现的'a',用'd'替换所有'c'。

I want to replace all occurrence of 'a' with 'b', and 'c' with 'd'.

我当前的解决方案是:

std::replace(str.begin(), str.end(), 'a', 'b');
std::replace(str.begin(), str.end(), 'c', 'd');

是否可以使用std在单个函数中进行操作?

Is it possible do it in single function using the std?

推荐答案

棘手的解决方案:

#include <algorithm>
#include <string>
#include <iostream>
#include <map>

int main() {
   char r; //replacement
   std::map<char, char> rs = { {'a', 'b'}, {'c', 'd'} };
   std::string s = "abracadabra";
   std::replace_if(s.begin(), s.end(), [&](char c){ return r = rs[c]; }, r);
   std::cout << s << std::endl;
}

编辑

为取悦所有效率根基,我们可以更改解决方案,以免为每个不存在的键附加 rs 映射,同时保持棘手的风味。可以按照以下步骤进行操作:

To please all efficiency radicals one can change the solution, to not to append rs map for each non existing key, while remain tricky flavor untouched. This can be done as follows:

#include <algorithm>
#include <string>
#include <iostream>
#include <map>

int main() {
   char r; //replacement
   std::map<char, char> rs = { {'a', 'b'}, {'c', 'd'} };
   std::string s = "abracadabra";
   std::replace_if(s.begin(), s.end(), [&](char c){ return (rs.find(c) != rs.end())
                                                        && (r = rs[c]); }, r); 
   std::cout << s << std::endl; //bbrbdbdbbrb
}

[实时演示]

这篇关于替换字符串中的多对字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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