替换字符串中的多对字符

Hum*_*awi 3 c++ string std c++11

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

我目前的解决方案是:

std::replace(str.begin(), str.end(), 'a', 'b');
std::replace(str.begin(), str.end(), 'c', 'd');
Run Code Online (Sandbox Code Playgroud)

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

Ana*_*lyS 6

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

 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;
  });
Run Code Online (Sandbox Code Playgroud)


W.F*_*.F. 5

棘手的解决方案:

#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;
}
Run Code Online (Sandbox Code Playgroud)

编辑

为了取悦所有效率根基,人们可以改变解决方案,不rs为每个不存在的键附加地图,同时保持棘手的风味。可以按照以下步骤进行:

#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
}
Run Code Online (Sandbox Code Playgroud)

[现场演示]

  • 只是备注:`std :: map :: operator []`如果给定键的对应值不存在,则将新构造的默认元素追加到映射本身。因此,通过@WF解决方案,`rs`的大小会随着不匹配字符数的增加而增加。 (2认同)