package cn.sounderx.text01;
import sun.security.ssl.Debug;
/*
* 数法的实现
* */
public class SoundexSimple {
public static void main(String[] args) {
String [] name = { "Darwin,Ian",
"Davidson, Greg",
"Darweent,William",
"Derwin,Daemon"};
for(int i = 0;i < name.length; i++){
//System.out.println("未改变之前:"+name[i]);
System.out.println(Soundex.soundex(name[i]) +' '+ name[i]);
}
}
}
class Soundex{ //A B C D E F G H I J K L M N O P W R S T U V W X Y Z 实现映射
public static final char[] MAP = {'0','1','2','3','0','1','2','0','0','2','2','4','5','5','0','1','2','6','2','3','0','1','0','2','0','2' };
public static String soundex(String s){ //将给定的字符串转换成对应的字符编码
String t = s.toUpperCase(); //转换成对应的大写字母
StringBuffer res = new StringBuffer();
char c, prev= '?';//主循环,找出映射的字符(最多有4个)检查给定的字符是否为字母
for(int i = 0; i <t.length() && res.length() < 4 && (c = t.charAt(i)) != ','; i++){
if(c >='A' && c <='Z' && c !=prev){
prev =c;
if(i == 0){res.append(c);}
else{
char m = MAP[c-'A'];
Debug.println("inner", c +"-->"+m);
if(m !='0') res.append(m);
}
}
}
if(res.length() ==0)return null;
for(int i = res.length(); i < 4; i++)res.append('0');
return res.toString();
}
}