c# Alpha Telephone Number Translator

前端 未结 5 1776
忘掉有多难
忘掉有多难 2021-01-28 01:35

I have a homework assignment where the program will accept any phone number in the format similar to 555-GET-FOOD. The task is to map the alphabetic letters to numbers and tran

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-28 02:16

    using System;
    
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine(AlphaPhoneToNumber("555-GET-FOOD"));
        }
    
        public static string AlphaPhoneToNumber(string val){
            //strings are immutable so let's get the array version of the value
            var phoneNumberArr = val.ToCharArray();
            for(int i = 0; i < val.Length; i++){
                phoneNumberArr[i] = AlphaPhoneCharToNumber(phoneNumberArr[i]);
            }
            return new string(phoneNumberArr);
        }
    
        public static char AlphaPhoneCharToNumber(char val){
            switch(val){
                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':
                    return '7';
                case 'S':
                case 'T':
                case 'U':
                    return '8';
                case 'V':
                case 'W':
                case 'X':
                case 'Y':
                case 'Z':
                    return '9';
                default: return val;
    
            }
        }
    }
    

    and here's how to do it without switch:

    public static char AlphaPhoneCharToNumber2(char val){
        // All three arrays are of exact same length
        var ualphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
        var lalphas = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
        var numval =  "22233344455566677788899999".ToCharArray();
        // thus I will loop up to the max length of one of the arrays
        // remember they are all the same length
        for(int i = 0; i < ualphas.Length; i++){
            //I will check if the value is in one of the alphabet
            //arrays at the current index
            //if there is a match I will assign it the number value
            //at the same index
            // MATCH UPPER?         MATCH LOWER?              RETURN NUMBER
            if(ualphas[i] == val || lalphas[i] == val) return numval[i];
        }
        // ELSE RETURN THE ORIGINAL VALUE
        return val;
    }
    

提交回复
热议问题