1

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 ?

0

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.