Skip to content

Instantly share code, notes, and snippets.

@FUNExtreme
Last active August 29, 2015 14:23
Show Gist options
  • Save FUNExtreme/f9e73039cce93ccc4d5d to your computer and use it in GitHub Desktop.
Save FUNExtreme/f9e73039cce93ccc4d5d to your computer and use it in GitHub Desktop.
Translates a phone number with phoneword letters to a numeric phone number
public static class Phoneword
{
/// <summary>
/// Translates a phonenumber that might contain phoneword letters to the corresponding number
/// NOTE: Expects a valid phone number
/// </summary>
/// <param name="c">The character to translate to the corresponding number</param>
/// <returns>String with the translated phonenumber</returns>
public static string Translate(string rawPhoneNumber)
{
StringBuilder newPhoneNumber = new StringBuilder();
// Prepare number, should be uppercase (eg: 123 JOHN)
rawPhoneNumber.ToUpperInvariant();
// Loop the phone number string and translate the characters that require translation
int phoneNumberLength = rawPhoneNumber.Length;
for(int x = 0; x < phoneNumberLength; x ++)
{
// Check if we need to translate the current character
if(rawPhoneNumber[x] >= 'A' && rawPhoneNumber[x] <= 'Z')
{
int nmbr = TranslateLetterToNumber(c);
newPhoneNumber.Append(nmbr);
}
else
newPhoneNumber.Append(c);
}
return newPhoneNumber.ToString();
}
/// <summary>
/// Translates a Phoneword letter to the corresponding number
/// </summary>
/// <param name="c">The character to translate to the corresponding number</param>
private static int TranslateLetterToNumber(char c)
{
switch(c)
{
case 'A':
case 'B':
case 'C':
return 2;
case 'D':
case 'E':
case 'F':
return 3;
case 'G':
case 'H':
case 'I':
return 4;
case 'J':
case 'K':
case 'L':
return 5;
case 'M':
case 'N':
case 'O':
return 6;
case 'P'
case 'Q'
case 'R'
case 'S':
return 7;
case 'T':
case 'U':
case 'V':
return 8;
case 'W':
case 'X':
case 'Y':
case 'Z':
return 9;
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment