c# Alpha Telephone Number Translator

前端 未结 5 1548
忘掉有多难
忘掉有多难 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条回答
  •  梦毁少年i
    2021-01-28 02:19

    While "map" (implemented as Dictionary in C#/.Net) is probably best choice for this problem, basic math is enough for such simple transformation:

     Console.WriteLine(String.Join("",  // combine characters back to string
           "555-GET-FOOD" //value
              .ToUpperInvariant() // carefully converting to avoid Turkish I problems
              .Select(c=> (c>='A' && c<='Z') ? // only tweak A-Z range
                 Math.Min((c-'A')/3+2,9).ToString()[0] : c)))
    

提交回复
热议问题