fork download
  1. #include <iterator>
  2. #include <iostream>
  3.  
  4. template <typename In, typename Out>
  5. Out t9_transform(In f, In l, Out out)
  6. {
  7. auto magic = [](decltype(*f) i) { return '2' + std::min(7, (i - (i >> 4)) / 3); };
  8. decltype(0+*f) previous = 0;
  9.  
  10. for(;f!=l;++f) {
  11. if (*f>='a' && *f<='z') {
  12. auto idx = *f - 'a';
  13.  
  14. auto digit = magic(idx);
  15. if (digit == previous) *out++ = ' ';
  16. previous = digit;
  17.  
  18. static_assert(std::is_signed<decltype(idx)>::value, "difference type is required to be signed here");
  19. for (; idx>=0 && digit == magic(idx); --idx)
  20. *out++ = digit;
  21. } else
  22. *out++ = '0';
  23. }
  24.  
  25. return out;
  26. }
  27.  
  28. std::string t9(std::string const& input)
  29. {
  30. std::string result;
  31. // result.reserve(2*input.size());
  32. t9_transform(begin(input), end(input), std::back_inserter(result));
  33. return result;
  34. }
  35.  
  36. int main()
  37. {
  38. const std::string input = "abcdefghijklmnopqrstuvwxyz";
  39. auto output = t9_transform(begin(input), end(input), std::ostream_iterator<char>(std::cout));
  40.  
  41. std::cout << std::endl << t9("hello world!") << std::endl;
  42.  
  43. // or, how about translating all of stdin to stdout, in streaming mode?
  44. *t9_transform(std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>(), output) = '\n';
  45. }
  46.  
Success #stdin #stdout 0s 2992KB
stdin
some poetry wouldn't be remiss
stdout
2 22 2223 33 3334 44 4445 55 5556 66 6667 77 777 77778 88 8889 99 999 9999
4433555 5556660966677755530
7777666 633076663387779990 966688555366080223307773364447777 7777