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?
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
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;
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With