0

I need to compare two strings and find out if they're similar or not, and how much. For example I have a String "5000002105416", and compared to "5000003205416" it should give me the result 0.85 as there are only 2 symbols that do not match in both strings which contain 13 symbols. The reason is that I'm using Zbar for barcode scanning and sometimes it gives me a bit wrong result, and I need to check whether this result is similar to some hardcoded tags that I need to be matched.

Roman Samoilenko
  • 932
  • 12
  • 25

3 Answers3

4

Let assume your Strings have the same length, so you need a function that iterate through both of them, comparing each char and find the number of differences:

double similarity(String a, String b) {
    if(a.length() == 0) return 1;
    int numberOfSimilarities = 0;
    for(int i = 0; i < a.length(); ++i) {
        if(a.charAt(i) == b.charAt(i)) {
            ++numberOfSimilarities;
        }
    }
    return (double) numberOfSimilarities / a.length();
}
Masked Man
  • 2,176
  • 2
  • 22
  • 41
0

You could easily have a method like:

public static double compare(String string, String compareString){
    int length = string.length();
    int comLength = compareString.length();
    int max = length;
    int min = comLength;
    int result = 0;
    if (length < comLength){
        max = comLength;
        min = length;
    }

    for(int index = 0; index < min; index++){
        if(string.charAt(index) == compareString.charAt(index)){
            result++;
        }
    }
    return (double)(result)/ (double)(max);
}

This will throw a few errors if you insert null or empty string, so if you do not want that then you can add some checks that return 0 like:

if(string.isEmpty()){
    if(compareString.isEmpty()){
        return 1;
    }
    return  0;
}else if(compareString.isEmpty()){
    return 0;
}

Or something like that. You could use a similar logic to prevent nulls too.

nick zoum
  • 7,216
  • 7
  • 36
  • 80
0
String a, b;
int count = 0;
for(int i = 0; i<13; i++){
    if(a.charAt(i)==b.charAt(i)) count++;
}
System.out.println(count/13.0);
talex
  • 17,973
  • 3
  • 29
  • 66