Replace multiple pair of characters in string

后端 未结 2 1036
情书的邮戳
情书的邮戳 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 09:06

    Tricky solution:

    #include 
    #include 
    #include 
    #include 
    
    int main() {
       char r; //replacement
       std::map 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 
    #include 
    #include 
    #include 
    
    int main() {
       char r; //replacement
       std::map 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]

提交回复
热议问题