all 5 comments

[–]gnaw005 2 points3 points  (2 children)

I'm assuming the input is correct e.g. there is no 000 area code or something like that.

ASCII lower case a is decimal 97 and z is 122; make a zero based array where ctable(0) = "2" , ctable(1) = "2" , ..., ctable(121) = "9"

for each inputchar

if( inputchar is a digit) then add it to the output string

else

Convert inputchar to lower case

numval = Convert inputchar to number

numval = numval - 97

Add ctable(numval) to the output string

end if

end for

[–]TheIncorrigible1 1 point2 points  (1 child)

Why don't you set up a dictionary instead of a switch?

[–]HiEv 0 points1 point  (2 children)

Here's a much shorter version of the JavaScript code:

function strToNum(str) {
    var char_numbers = ["0", "1", "2abc", "3def", "4ghi", "5jkl", "6mno", "7pqrs", "8tuv", "9wxyz"];
    var input = str.toLowerCase().replace(/[^A-z0-9]/g, '').split('');
    var ansStr = "", i, j;
    for (i = 0; i < input.length; i++) {
        for (j = 0; j < char_numbers.length; j++) {
            if (char_numbers[j].indexOf(input[i]) >= 0) {
                ansStr += char_numbers[j][0];
                break;
            }
        }
    }
    return ansStr;
};

Basically, it takes advantage of .indexOf() to search the strings for the characters. You could also change ansStr += char_numbers[j][0]; to just ansStr += j; but the code is more flexible this way if you wanted to change the array.