Skip to content

Instantly share code, notes, and snippets.

@nop
Last active February 1, 2023 10:59
Show Gist options
  • Save nop/138bd2e7ef0785df2a7428f1564c6761 to your computer and use it in GitHub Desktop.
Save nop/138bd2e7ef0785df2a7428f1564c6761 to your computer and use it in GitHub Desktop.
Translate a string into a telephone keypad code
using System.Collections.Generic;
using System.Text;
static string TranslateToNumber(string input)
{
var map = new Dictionary<char, char>
{
{'a', '2'}, {'b', '2'}, {'c', '2'},
{'d', '3'}, {'e', '3'}, {'f', '3'},
{'g', '4'}, {'h', '4'}, {'i', '4'},
{'j', '5'}, {'k', '5'}, {'l', '5'},
{'m', '6'}, {'n', '6'}, {'o', '6'},
{'p', '7'}, {'q', '7'}, {'r', '7'}, {'s', '7'},
{'t', '8'}, {'u', '8'}, {'v', '8'},
{'w', '9'}, {'x', '9'}, {'y', '9'}, {'z', '9'}
};
var result = new StringBuilder();
foreach (var c in input)
{
result.Append(map.TryGetValue(c, out var value) ? value : c);
}
return result.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment