Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert Alphanumeric phone number

I've been working on this issue for awhile and I've been stuck so I hope someone can push me in the right direction. I have a c# console application that will take in a string and verify that it contains only 0-9, a-z, A-Z, and -.

My issue that I'm having is that I need to convert any letters in the phone number to their respective number. So if I input 1800-Flowers, it will output as 1800-3569377. I have my methods defined:

I'm not looking for the solutions here (this is homework), but I'm looking for a push in the right direction. Do I need to convert the string to a char array to break up each individual character, and then use that in the convert method to switch any letter into a number?

like image 941
fdsa Avatar asked Feb 20 '14 18:02

fdsa


3 Answers

There are certainly a lot of solutions here. Since you're already using Regex, you could approach it in a basic way:

num = Regex.Replace(num, @"[abcABC]", "2");
num = Regex.Replace(num, @"[defDEF]", "3");
//....

or you could create a Dictionary<string,char> and run through each char and convert it to the mapped character. Something like :

var dict = new Dictionary<string, char>(); 
dict.Add("abcABC",'2');
//...

foreach(char c in num.Where(char.IsLetter))
{
    var digit = dict.First(d => d.Key.Contains(c)).Value;
    num = num.Replace(c, digit);
} 

Like you said, the LINQ here is splitting the string to a char array, and looping through ones that are letters

like image 56
Jonesopolis Avatar answered Oct 08 '22 23:10

Jonesopolis


Since this is for school, i'm sure you can't go crazy with more advanced topics. Lets keep it simple with a switch/case.

You can map the letters to their corresponding number first, just use a switch/case to find the correct number depending on the letter.

For example:

String phoneNumber = "1800ab";

for(int x=0; x < phoneNumber.Length; x++)
{
   if(Char.IsLetter(phoneNumber[x]))
   {
      switch(phoneNumber[x].ToString().ToLower())
      {
         case "a":
         case "b":
         case "c":
           //This is number 2!
         break;


      }
   }
}
like image 38
Dayan Avatar answered Oct 09 '22 00:10

Dayan


String already implements IEnumerable<char> - so no need to "break up" there.

Mapping of something to something (like letter code to matching number) is generally done with map (associative array) types (in C#/.Net it is Dictionary) that provide mapping one value ("key") to corresponding "value" - consider using that.

like image 42
Alexei Levenkov Avatar answered Oct 09 '22 01:10

Alexei Levenkov