fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <cassert>
  4. #include <utility>
  5.  
  6. struct translator
  7. {
  8. translator(std::string src, std::string tgt)
  9. : _source(std::move(src)), _target(std::move(tgt))
  10. {
  11. assert(_source.length() == _target.length());
  12. }
  13.  
  14.  
  15. char operator()(char ch) const;
  16.  
  17. private:
  18. std::string _source;
  19. std::string _target;
  20. };
  21.  
  22.  
  23. // if ch is found in _source, return the corresponding character in _target
  24. // if it isn't found in _source, return ch
  25. char translator::operator()(char ch) const
  26. {
  27. auto pos = _source.find(ch);
  28. return pos == std::string::npos ? ch : _target[pos];
  29. }
  30.  
  31. // helper function. Applies translator to every element in a string.
  32. std::string translate(const translator& xlate, std::string s)
  33. {
  34. for (auto& ch : s)
  35. ch = xlate(ch);
  36.  
  37. return s;
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43. translator xlator("0123456789", "ABCDEFGHIJ");
  44.  
  45. std::string line;
  46.  
  47. while (std::getline(std::cin, line) && !line.empty())
  48. std::cout << translate(xlator, line) << '\n';
  49. }
Success #stdin #stdout 0s 3480KB
stdin
hi123
3403 1445 8S 34L828OUS
stdout
hiBCD
DEAD BEEF IS DELICIOUS