What is the best way to approach translating this code into Java? (the section called Convert Alpha-numeric Phone Number to All Numeric) http://lawrence.ecorp.net/inet/samples/regexp-format.php

Since Java doesn't have a lambda yet... what is the best approach for the String.replace ?

link|improve this question

71% accept rate
feedback

2 Answers

up vote 1 down vote accepted

Wow, the original code is a bit over-verbose. I'd do:

return phoneStr.replace(/[a-zA-Z]/g, function(m) {
    var ix= m[0].toLowerCase().charCodeAt(0)-0x61; // ASCII 'a'
    return '22233344455566677778889999'.charAt(ix);
});

And consequently in Java, something like:

StringBuffer b= new StringBuffer();
Matcher m= Pattern.compile("[A-Za-z]").matcher(phoneStr);
while (m.find()) {
    int ix= (int) (m.group(0).toLowerCase().charAt(0)-'a');
    m.appendReplacement(b, "22233344455566677778889999".substring(ix, ix+1));
}
m.appendTail(b);
return b.toString();

Replacing with Java's Matcher is clumsy enough that you might just prefer to use an array for this case:

char[] c= phoneStr.toLowerCase().toCharArray();
for (int i= 0; i<c.length; i++)
    if (c[i]>='a' && c[i]<='z')
        c[i]= "22233344455566677778889999".charAt((int) (c[i]-'a'));
return new String(c);
link|improve this answer
feedback

A very basic way to do this would be :

String replaceCharsByNumbers(String stringToChange) {
    return stringToChange
            .replace('a', '2')
            .replace('b', '2')
            .replace('c', '2')
            .replace('d', '3')
            .replace('e', '3')
            .replace('f', '3')
            .replace('g', '4')
            .replace('h', '4')
            .replace('i', '4')
            .replace('j', '5')
            .replace('k', '5')
            .replace('l', '5')
            .replace('m', '6')
            .replace('n', '6')
            .replace('o', '6')
            .replace('p', '7')
            .replace('q', '7')
            .replace('r', '7')
            .replace('s', '7')
            .replace('t', '8')
            .replace('u', '8')
            .replace('v', '8')
            .replace('w', '9')
            .replace('x', '9')
            .replace('y', '9')
            .replace('z', '9');
}
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.