5

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');
std::replace(str.begin(), str.end(), 'c', 'd');

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

1
  • Look up regular expressions. You may be able to use regular expressions to replace the letters with one statement. However, it may be more complicated than your 2 statement solution. Commented Jun 21, 2016 at 18:48

2 Answers 2

9

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]

Sign up to request clarification or add additional context in comments.

1 Comment

Just a remark: std::map::operator[] newly appends a default constructed element to the map itself if the corresponding value to the given key does not exist. So with this solution by @W.F, the size of rs increases as the number of unmatched characters.
8

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.