2010-09-16 167 views

回答

2

哇,原来的代码是一个有点冗长过。我会做:

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

并因此在Java中,是这样的:

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(); 

Java的匹配器的更换是不够,你可能只是喜欢使用这种情况下,阵列笨拙:

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); 
1

一个非常基本的方式做,这将是:

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