Replace multiple pair of characters in string

后端 未结 2 1026
情书的邮戳
情书的邮戳 2021-01-14 08:37

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

My current solution is:

std::replace(str.begin(), str.end(), \'a\', \'b\'         


        
相关标签:
2条回答
  • 2021-01-14 08:48

    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;
      });
    
    0 讨论(0)
  • 2021-01-14 09:06

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

    Edit

    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
    }
    

    [live demo]

    0 讨论(0)
提交回复
热议问题