KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > string > util > Soundex


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

16 // Copied from GenerationJava Core Library.
17
//package com.generationjava.util;
18

19 package org.apache.taglibs.string.util;
20
21 /**
22  * Find the Soundex of a string. Needs internationalisation in a
23  * future release.
24  *
25  * @author bayard@generationjava.com
26  * @version 0.4, 20010812
27  */

28 public class Soundex {
29
30     static public final char[] US_ENGLISH_MAPPING =
31         "01230120022455012623010202".toCharArray();
32
33     static public final Soundex US_ENGLISH = new Soundex();
34     
35     private char[] soundexMapping;
36
37     public Soundex() {
38         this(US_ENGLISH_MAPPING);
39     }
40
41     public Soundex(char[] mapping) {
42         this.soundexMapping = mapping;
43     }
44
45     /**
46      * Get the SoundEx value of a string.
47      * This implementation is taken from the code-snippers on
48      * http://www.sourceforge.net/
49      */

50     public String JavaDoc soundex(String JavaDoc str) {
51         char out[] = { '0', '0', '0', '0' };
52         char last, mapped;
53         int incount = 1, count = 1;
54         out[0] = Character.toUpperCase( str.charAt(0) );
55         last = getMappingCode( str.charAt(0) );
56         while( (incount < str.length() ) &&
57                (mapped = getMappingCode(str.charAt(incount++))) != 0 &&
58                (count < 4) )
59         {
60             if( (mapped != '0') && (mapped != last) ) {
61                 out[count++] = mapped;
62             }
63             last = mapped;
64         }
65         return new String JavaDoc(out);
66     }
67
68     /**
69      * Used internally by the SoundEx algorithm.
70      */

71     private char getMappingCode(char c) {
72         if( !Character.isLetter(c) ) {
73             return 0;
74         } else {
75             return soundexMapping[Character.toUpperCase(c) - 'A'];
76         }
77     }
78
79 }
80
Popular Tags