00001
package com.quadcap.util.text;
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046 public class Soundex {
00047 static final OctetMap alpha =
new OctetMap(
'a',
'z');
00048 static final OctetMap
Alpha =
new OctetMap(
'A',
'Z');
00049
static {
00050
Alpha.
include(
'a',
'z');
00051 }
00052
00053
00054 static final String
sMap =
"01230120022455012623010202";
00055 static final char scode(
int c) {
00056
if (
alpha.
has(c)) {
00057
return sMap.charAt(c -
'a');
00058 }
else {
00059
return sMap.charAt(c -
'A');
00060 }
00061 }
00062
00063 public static final String
soundex(String s) {
00064
char[] ret =
new char[4];
00065
char last =
'x';
00066
int pos = 0;
00067
for (
int i = 0; i < s.length() && pos < 4; i++) {
00068
int c = s.charAt(i) & 0xff;
00069
if (
Alpha.
has(c)) {
00070
if (pos == 0) {
00071 ret[pos++] = Character.toUpperCase((
char)c);
00072 }
else {
00073
char code = scode(c);
00074
if (code !=
'0' && code != last) {
00075 ret[pos++] = code;
00076 last = code;
00077 }
00078 }
00079 }
00080 }
00081
if (pos == 0)
return "";
00082
while (pos < 4) ret[pos++] =
'0';
00083
return new String(ret);
00084 }
00085
00086 public static final int difference(String a, String b) {
00087 String sa = soundex(a);
00088 String sb = soundex(b);
00089
int diff = 0;
00090
for (
int i = 0; i < 4; i++) {
00091
if (sa.charAt(i) == sb.charAt(i)) diff++;
00092 }
00093
return diff;
00094 }
00095
00096
00097 static String[]
data = {
00098
"blather",
"blabber",
"Smith",
"Smyth",
00099
"abcdefghijklmnopqrstuvwxyz",
"a",
"b",
"bed",
"BBD",
00100
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"smithers",
"smothers",
"brothers"
00101 };
00102 public static void main(String[] args) {
00103
for (
int i = 0; i <
data.length; i++) {
00104 System.out.println(soundex(
data[i]) +
": " +
data[i]);
00105 }
00106 }
00107
00108 }