How to convert an alphanumeric phone number to digits

前端 未结 7 925
臣服心动
臣服心动 2021-01-05 12:50

UPDATE:

The final version of my utility looks like this:

StringBuilder b = new StringBuilder();

for(char c : inLetters.toLowerCase(         


        
7条回答
  •  鱼传尺愫
    2021-01-05 13:17

    The switch statement is not really that bad. Your algorithm is linear with respect to the length of the phone number. The code is readable and pretty easy to verify by inspection. I wouldn't mess with it, except to add a default case for handling errors. (I'm not a Java programmer, so forgive me if it's called something else.)

    If you have to make it faster, a pre-initialized table indexed by character would avoid any comparisons beyond basic error checking. You could even avoid the case conversion by duplicating the values in the table (digit['A'] = digit['a'] = "2";). The cost of initializing the table would be amortized over the total number of conversions.

提交回复
热议问题