IntroductionIf we observe the phone keypad, the phone numbers are mapped to letters as 2 - ABC , 3 -DEF , 4-GHI, 5-JKL, 6-MNO, 7-PQRS, 8-TUV, 9-WXYZ . In this snippet we will write a program which converts letters on phone to numbers using .NET. Program:class PhoneLetterToNumberConversion
{
static void Main(string[] args)
{
Dictionary<char, char> dicPhoneNoLetterMap = 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' }
};
Console.WriteLine(ConvertLettersToPhoneNumbers("ADHK", dicPhoneNoLetterMap));
Console.WriteLine(ConvertLettersToPhoneNumbers("DOTNETMIRROR", dicPhoneNoLetterMap));
Console.Read();
}
static string ConvertLettersToPhoneNumbers(string letters, Dictionary<char, char> dicPhoneNoLetterMap)
{
char[] numbersChrArray = new char[letters.Length]; // create new char array with length of input string
for (int i = 0; i < numbersChrArray.Length; i++)
{
char number;
bool hasValue = dicPhoneNoLetterMap.TryGetValue(letters[i], out number);//check dictionary has Key Value
if (hasValue)
{
numbersChrArray[i] = number;
}
else
{
numbersChrArray[i] = letters[i];
}
}
string finalNumber = new string(numbersChrArray);
return finalNumber;
}
} Output:"ADHK" - 2345 "DOTNETMIRROR" - 368638647767
|