001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.apache.commons.codec.language; 019 020import org.apache.commons.codec.EncoderException; 021import org.apache.commons.codec.StringEncoder; 022 023/** 024 * Encodes a string into a Soundex value. Soundex is an encoding used to relate similar names, but can also be used as a 025 * general purpose scheme to find word with similar phonemes. 026 * 027 * This class is thread-safe. 028 * Although not strictly immutable, the {@link #maxLength} field is not actually used. 029 * 030 * @version $Id: Soundex.html 928559 2014-11-10 02:53:54Z ggregory $ 031 */ 032public class Soundex implements StringEncoder { 033 034 /** 035 * This is a default mapping of the 26 letters used in US English. A value of <code>0</code> for a letter position 036 * means do not encode. 037 * <p> 038 * (This constant is provided as both an implementation convenience and to allow Javadoc to pick 039 * up the value for the constant values page.) 040 * </p> 041 * 042 * @see #US_ENGLISH_MAPPING 043 */ 044 public static final String US_ENGLISH_MAPPING_STRING = "01230120022455012623010202"; 045 046 /** 047 * This is a default mapping of the 26 letters used in US English. A value of <code>0</code> for a letter position 048 * means do not encode. 049 * 050 * @see Soundex#Soundex(char[]) 051 */ 052 private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); 053 054 /** 055 * An instance of Soundex using the US_ENGLISH_MAPPING mapping. 056 * 057 * @see #US_ENGLISH_MAPPING 058 */ 059 public static final Soundex US_ENGLISH = new Soundex(); 060 061 /** 062 * The maximum length of a Soundex code - Soundex codes are only four characters by definition. 063 * 064 * @deprecated This feature is not needed since the encoding size must be constant. Will be removed in 2.0. 065 */ 066 @Deprecated 067 private int maxLength = 4; 068 069 /** 070 * Every letter of the alphabet is "mapped" to a numerical value. This char array holds the values to which each 071 * letter is mapped. This implementation contains a default map for US_ENGLISH 072 */ 073 private final char[] soundexMapping; 074 075 /** 076 * Creates an instance using US_ENGLISH_MAPPING 077 * 078 * @see Soundex#Soundex(char[]) 079 * @see Soundex#US_ENGLISH_MAPPING 080 */ 081 public Soundex() { 082 this.soundexMapping = US_ENGLISH_MAPPING; 083 } 084 085 /** 086 * Creates a soundex instance using the given mapping. This constructor can be used to provide an internationalized 087 * mapping for a non-Western character set. 088 * 089 * Every letter of the alphabet is "mapped" to a numerical value. This char array holds the values to which each 090 * letter is mapped. This implementation contains a default map for US_ENGLISH 091 * 092 * @param mapping 093 * Mapping array to use when finding the corresponding code for a given character 094 */ 095 public Soundex(final char[] mapping) { 096 this.soundexMapping = new char[mapping.length]; 097 System.arraycopy(mapping, 0, this.soundexMapping, 0, mapping.length); 098 } 099 100 /** 101 * Creates a refined soundex instance using a custom mapping. This constructor can be used to customize the mapping, 102 * and/or possibly provide an internationalized mapping for a non-Western character set. 103 * 104 * @param mapping 105 * Mapping string to use when finding the corresponding code for a given character 106 * @since 1.4 107 */ 108 public Soundex(final String mapping) { 109 this.soundexMapping = mapping.toCharArray(); 110 } 111 112 /** 113 * Encodes the Strings and returns the number of characters in the two encoded Strings that are the same. This 114 * return value ranges from 0 through 4: 0 indicates little or no similarity, and 4 indicates strong similarity or 115 * identical values. 116 * 117 * @param s1 118 * A String that will be encoded and compared. 119 * @param s2 120 * A String that will be encoded and compared. 121 * @return The number of characters in the two encoded Strings that are the same from 0 to 4. 122 * 123 * @see SoundexUtils#difference(StringEncoder,String,String) 124 * @see <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp"> MS 125 * T-SQL DIFFERENCE </a> 126 * 127 * @throws EncoderException 128 * if an error occurs encoding one of the strings 129 * @since 1.3 130 */ 131 public int difference(final String s1, final String s2) throws EncoderException { 132 return SoundexUtils.difference(this, s1, s2); 133 } 134 135 /** 136 * Encodes an Object using the soundex algorithm. This method is provided in order to satisfy the requirements of 137 * the Encoder interface, and will throw an EncoderException if the supplied object is not of type java.lang.String. 138 * 139 * @param obj 140 * Object to encode 141 * @return An object (or type java.lang.String) containing the soundex code which corresponds to the String 142 * supplied. 143 * @throws EncoderException 144 * if the parameter supplied is not of type java.lang.String 145 * @throws IllegalArgumentException 146 * if a character is not mapped 147 */ 148 @Override 149 public Object encode(final Object obj) throws EncoderException { 150 if (!(obj instanceof String)) { 151 throw new EncoderException("Parameter supplied to Soundex encode is not of type java.lang.String"); 152 } 153 return soundex((String) obj); 154 } 155 156 /** 157 * Encodes a String using the soundex algorithm. 158 * 159 * @param str 160 * A String object to encode 161 * @return A Soundex code corresponding to the String supplied 162 * @throws IllegalArgumentException 163 * if a character is not mapped 164 */ 165 @Override 166 public String encode(final String str) { 167 return soundex(str); 168 } 169 170 /** 171 * Used internally by the SoundEx algorithm. 172 * 173 * Consonants from the same code group separated by W or H are treated as one. 174 * 175 * @param str 176 * the cleaned working string to encode (in upper case). 177 * @param index 178 * the character position to encode 179 * @return Mapping code for a particular character 180 * @throws IllegalArgumentException 181 * if the character is not mapped 182 */ 183 private char getMappingCode(final String str, final int index) { 184 // map() throws IllegalArgumentException 185 final char mappedChar = this.map(str.charAt(index)); 186 // HW rule check 187 if (index > 1 && mappedChar != '0') { 188 final char hwChar = str.charAt(index - 1); 189 if ('H' == hwChar || 'W' == hwChar) { 190 final char preHWChar = str.charAt(index - 2); 191 final char firstCode = this.map(preHWChar); 192 if (firstCode == mappedChar || 'H' == preHWChar || 'W' == preHWChar) { 193 return 0; 194 } 195 } 196 } 197 return mappedChar; 198 } 199 200 /** 201 * Returns the maxLength. Standard Soundex 202 * 203 * @deprecated This feature is not needed since the encoding size must be constant. Will be removed in 2.0. 204 * @return int 205 */ 206 @Deprecated 207 public int getMaxLength() { 208 return this.maxLength; 209 } 210 211 /** 212 * Returns the soundex mapping. 213 * 214 * @return soundexMapping. 215 */ 216 private char[] getSoundexMapping() { 217 return this.soundexMapping; 218 } 219 220 /** 221 * Maps the given upper-case character to its Soundex code. 222 * 223 * @param ch 224 * An upper-case character. 225 * @return A Soundex code. 226 * @throws IllegalArgumentException 227 * Thrown if <code>ch</code> is not mapped. 228 */ 229 private char map(final char ch) { 230 final int index = ch - 'A'; 231 if (index < 0 || index >= this.getSoundexMapping().length) { 232 throw new IllegalArgumentException("The character is not mapped: " + ch); 233 } 234 return this.getSoundexMapping()[index]; 235 } 236 237 /** 238 * Sets the maxLength. 239 * 240 * @deprecated This feature is not needed since the encoding size must be constant. Will be removed in 2.0. 241 * @param maxLength 242 * The maxLength to set 243 */ 244 @Deprecated 245 public void setMaxLength(final int maxLength) { 246 this.maxLength = maxLength; 247 } 248 249 /** 250 * Retrieves the Soundex code for a given String object. 251 * 252 * @param str 253 * String to encode using the Soundex algorithm 254 * @return A soundex code for the String supplied 255 * @throws IllegalArgumentException 256 * if a character is not mapped 257 */ 258 public String soundex(String str) { 259 if (str == null) { 260 return null; 261 } 262 str = SoundexUtils.clean(str); 263 if (str.length() == 0) { 264 return str; 265 } 266 final char out[] = {'0', '0', '0', '0'}; 267 char last, mapped; 268 int incount = 1, count = 1; 269 out[0] = str.charAt(0); 270 // getMappingCode() throws IllegalArgumentException 271 last = getMappingCode(str, 0); 272 while (incount < str.length() && count < out.length) { 273 mapped = getMappingCode(str, incount++); 274 if (mapped != 0) { 275 if (mapped != '0' && mapped != last) { 276 out[count++] = mapped; 277 } 278 last = mapped; 279 } 280 } 281 return new String(out); 282 } 283 284}