替换字符串中的多对字符

时间:2021-02-22 01:59:24

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

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

My current solution is:

我目前的解决方案是:

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

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

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

2 个解决方案

#1


1  

Tricky solution:

#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;}

#2


4  

If you do not like two passes, you can do it once:

如果你不喜欢两次通过,你可以做一次:

 std::transform(std::begin(s), std::end(s), std::begin(s), [](auto ch) {    switch (ch) {    case 'a':      return 'b';    case 'c':      return 'd';    }    return ch;  });

#1


1  

Tricky solution:

#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;}

#2


4  

If you do not like two passes, you can do it once:

如果你不喜欢两次通过,你可以做一次:

 std::transform(std::begin(s), std::end(s), std::begin(s), [](auto ch) {    switch (ch) {    case 'a':      return 'b';    case 'c':      return 'd';    }    return ch;  });