KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > text > correction > NameMatcher


1 /*******************************************************************************
2  * Copyright (c) 2000, 2005 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11
12
13 package org.eclipse.jdt.internal.ui.text.correction;
14
15 public class NameMatcher {
16
17     /**
18      * Returns a similarity value of the two names.
19      * The range of is from 0 to 256. no similarity is negative
20      */

21     public static boolean isSimilarName(String JavaDoc name1, String JavaDoc name2) {
22         return getSimilarity(name1, name2) >= 0;
23     }
24
25     /**
26      * Returns a similarity value of the two names.
27      * The range of is from 0 to 256. no similarity is negative
28      */

29     public static int getSimilarity(String JavaDoc name1, String JavaDoc name2) {
30         if (name1.length() > name2.length()) {
31             String JavaDoc tmp= name1;
32             name1= name2;
33             name2= tmp;
34         }
35         int name1len= name1.length();
36         int name2len= name2.length();
37
38         int nMatched= 0;
39
40         int i= 0;
41         while (i < name1len && isSimilarChar(name1.charAt(i), name2.charAt(i))) {
42             i++;
43             nMatched++;
44         }
45
46         int k= name1len;
47         int diff= name2len - name1len;
48         while (k > i && isSimilarChar(name1.charAt(k - 1), name2.charAt(k + diff - 1))) {
49             k--;
50             nMatched++;
51         }
52
53         if (nMatched == name2len) {
54             return 200;
55         }
56
57         if (name2len - nMatched > nMatched) {
58             return -1;
59         }
60
61         int tolerance= name2len / 4 + 1;
62         return (tolerance - (k - i)) * 256 / tolerance;
63     }
64
65     private static boolean isSimilarChar(char ch1, char ch2) {
66         return Character.toLowerCase(ch1) == Character.toLowerCase(ch2);
67     }
68
69 }
70
Popular Tags