字符串相似算法Soundex的Java实现

10 篇文章 0 订阅

Soundex是一种根据发音来计算相似度的一种算法。

public class Soundex {

	private static char[] chars=new char[]{'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'};
	private static int MAXCHARS=4;
	
	public static String getSoundexString(String word){
		
		char[] wordChars=null;
		char[] result=new char[4];
		if(word==null||(wordChars=word.trim().toCharArray()).length==0){
			return null;
		}
		//下标
		int index=-1;
		//当前位移
		int cur=0;
		//Soundex字符串已填充字符数
		int fill=0;
		while(cur<wordChars.length&&fill<MAXCHARS){
			char c=wordChars[cur++];
			if((c>='A'&&c<='Z')){
				index=c-'A';
				if(fill==0){
					c+='a'-'A';
				}
			}else if((c>='a'&&c<='z')){
				index=c-'a';
			}else{
				index=-1;
			}
			if(index!=-1){
				if(fill==0){
					result[fill++]=c;
				}else{
					char curChar=chars[index];
					if(curChar!='0'&&(fill==1||curChar!=result[fill-1])){
						result[fill++]=curChar;
					}
				}
			}
		}
		if(fill==0){
			return null;
		}
		for(int i=MAXCHARS-fill;i>0;i--){
			result[MAXCHARS-i]='0';
		}
		return new String(result);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值