2010-09-16 239 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'); 
}