RefinedSoundex.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.codec.language;

  18. import org.apache.commons.codec.EncoderException;
  19. import org.apache.commons.codec.StringEncoder;

  20. /**
  21.  * Encodes a string into a Refined Soundex value. A refined soundex code is
  22.  * optimized for spell checking words. Soundex method originally developed by
  23.  * <CITE>Margaret Odell</CITE> and <CITE>Robert Russell</CITE>.
  24.  *
  25.  * <p>This class is immutable and thread-safe.</p>
  26.  */
  27. public class RefinedSoundex implements StringEncoder {

  28.     /**
  29.      * Mapping:
  30.      * <pre>
  31.      * 0: A E I O U Y H W
  32.      * 1: B P
  33.      * 2: F V
  34.      * 3: C K S
  35.      * 4: G J
  36.      * 5: Q X Z
  37.      * 6: D T
  38.      * 7: L
  39.      * 8: M N
  40.      * 9: R
  41.      * </pre>
  42.      * @since 1.4
  43.      */
  44.     //                                                      ABCDEFGHIJKLMNOPQRSTUVWXYZ
  45.     public static final String US_ENGLISH_MAPPING_STRING = "01360240043788015936020505";

  46.    /**
  47.      * RefinedSoundex is *refined* for a number of reasons one being that the
  48.      * mappings have been altered. This implementation contains default
  49.      * mappings for US English.
  50.      */
  51.     private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray();

  52.     /**
  53.      * This static variable contains an instance of the RefinedSoundex using
  54.      * the US_ENGLISH mapping.
  55.      */
  56.     public static final RefinedSoundex US_ENGLISH = new RefinedSoundex();

  57.     /**
  58.      * Every letter of the alphabet is "mapped" to a numerical value. This char
  59.      * array holds the values to which each letter is mapped. This
  60.      * implementation contains a default map for US_ENGLISH
  61.      */
  62.     private final char[] soundexMapping;

  63.      /**
  64.      * Creates an instance of the RefinedSoundex object using the default US
  65.      * English mapping.
  66.      */
  67.     public RefinedSoundex() {
  68.         this.soundexMapping = US_ENGLISH_MAPPING;
  69.     }

  70.     /**
  71.      * Creates a refined soundex instance using a custom mapping. This
  72.      * constructor can be used to customize the mapping, and/or possibly
  73.      * provide an internationalized mapping for a non-Western character set.
  74.      *
  75.      * @param mapping
  76.      *                  Mapping array to use when finding the corresponding code for
  77.      *                  a given character
  78.      */
  79.     public RefinedSoundex(final char[] mapping) {
  80.         this.soundexMapping = mapping.clone();
  81.     }

  82.     /**
  83.      * Creates a refined Soundex instance using a custom mapping. This constructor can be used to customize the mapping,
  84.      * and/or possibly provide an internationalized mapping for a non-Western character set.
  85.      *
  86.      * @param mapping
  87.      *            Mapping string to use when finding the corresponding code for a given character
  88.      * @since 1.4
  89.      */
  90.     public RefinedSoundex(final String mapping) {
  91.         this.soundexMapping = mapping.toCharArray();
  92.     }

  93.     /**
  94.      * Returns the number of characters in the two encoded Strings that are the
  95.      * same. This return value ranges from 0 to the length of the shortest
  96.      * encoded String: 0 indicates little or no similarity, and 4 out of 4 (for
  97.      * example) indicates strong similarity or identical values. For refined
  98.      * Soundex, the return value can be greater than 4.
  99.      *
  100.      * @param s1
  101.      *                  A String that will be encoded and compared.
  102.      * @param s2
  103.      *                  A String that will be encoded and compared.
  104.      * @return The number of characters in the two encoded Strings that are the
  105.      *             same from 0 to the length of the shortest encoded String.
  106.      *
  107.      * @see SoundexUtils#difference(StringEncoder,String,String)
  108.      * @see <a href="https://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp">
  109.      *          MS T-SQL DIFFERENCE</a>
  110.      *
  111.      * @throws EncoderException
  112.      *                  if an error occurs encoding one of the strings
  113.      * @since 1.3
  114.      */
  115.     public int difference(final String s1, final String s2) throws EncoderException {
  116.         return SoundexUtils.difference(this, s1, s2);
  117.     }

  118.     /**
  119.      * Encodes an Object using the refined soundex algorithm. This method is
  120.      * provided in order to satisfy the requirements of the Encoder interface,
  121.      * and will throw an EncoderException if the supplied object is not of type
  122.      * {@link String}.
  123.      *
  124.      * @param obj
  125.      *                  Object to encode
  126.      * @return An object (or type {@link String}) containing the refined
  127.      *             soundex code which corresponds to the String supplied.
  128.      * @throws EncoderException
  129.      *                  if the parameter supplied is not of type {@link String}
  130.      */
  131.     @Override
  132.     public Object encode(final Object obj) throws EncoderException {
  133.         if (!(obj instanceof String)) {
  134.             throw new EncoderException("Parameter supplied to RefinedSoundex encode is not of type java.lang.String");
  135.         }
  136.         return soundex((String) obj);
  137.     }

  138.     /**
  139.      * Encodes a String using the refined soundex algorithm.
  140.      *
  141.      * @param str
  142.      *                  A String object to encode
  143.      * @return A Soundex code corresponding to the String supplied
  144.      */
  145.     @Override
  146.     public String encode(final String str) {
  147.         return soundex(str);
  148.     }

  149.     /**
  150.      * Returns the mapping code for a given character. The mapping codes are
  151.      * maintained in an internal char array named soundexMapping, and the
  152.      * default values of these mappings are US English.
  153.      *
  154.      * @param c
  155.      *                  char to get mapping for
  156.      * @return A character (really a numeral) to return for the given char
  157.      */
  158.     char getMappingCode(final char c) {
  159.         if (!Character.isLetter(c)) {
  160.             return 0;
  161.         }
  162.         final int index = Character.toUpperCase(c) - 'A';
  163.         if (index < 0 || index >= this.soundexMapping.length) {
  164.             return 0;
  165.         }
  166.         return this.soundexMapping[index];
  167.     }

  168.     /**
  169.      * Retrieves the Refined Soundex code for a given String object.
  170.      *
  171.      * @param str
  172.      *                  String to encode using the Refined Soundex algorithm
  173.      * @return A soundex code for the String supplied
  174.      */
  175.     public String soundex(String str) {
  176.         if (str == null) {
  177.             return null;
  178.         }
  179.         str = SoundexUtils.clean(str);
  180.         if (str.isEmpty()) {
  181.             return str;
  182.         }

  183.         final StringBuilder sBuf = new StringBuilder();
  184.         sBuf.append(str.charAt(0));

  185.         char last, current;
  186.         last = '*';

  187.         for (int i = 0; i < str.length(); i++) {

  188.             current = getMappingCode(str.charAt(i));
  189.             if (current == last) {
  190.                 continue;
  191.             }
  192.             if (current != 0) {
  193.                 sBuf.append(current);
  194.             }

  195.             last = current;

  196.         }

  197.         return sBuf.toString();
  198.     }
  199. }