Theja
Theja

Reputation: 762

Finding number of mismatches between two strings

I am needed find number of mismatching characters between two strings. Currently i m doing it by converting strings into char Arrays and comparing element by element.

Is there any other way to achieve above requirement.

Note: consider string as lower case

Inputs :

input

utput

Output :

2

Upvotes: 1

Views: 4401

Answers (3)

user3377716
user3377716

Reputation:

This is the way you are describing, but it is the simplest way of implementing:

int counter = 0;
for(int i = 0; i < str1.length(); i++) if(str1.charAt(i) != str2.charAt(i)) counter++;

They can be fit on just two lines of code, without explicitly creating a whole new character array.

Upvotes: 0

JHS
JHS

Reputation: 7871

If the two string are of different size the following code you return the total mismatch of alphabets.

You can try this -

    String ip1 = "input"; // input1
    String ip2 = "utput"; // input2
    int count = 0; // difference in string
    String ipx2 = ip2;
    for (int j = 0; j <= ip2.length(); j++) {
        int value = ip1.indexOf(ipx2);
        if (value != -1) {
            if (("").equals(ipx2)) { // if the second string is blank after continous reducing
                count = ip1.length() + ip2.length();
            } else {
                count = ip1.length() + ip2.length() - 2 * ipx2.length();
            }
            break;
        } else {
            count = ip1.length() + ip2.length(); // if there is no match at all
        }
        ipx2 = ip2.substring(j);
    }
    System.out.println("" + count);
}

You will have to check whether the inputs have some data or not. I have not done that check.

Upvotes: 0

tobiasbayer
tobiasbayer

Reputation: 10379

StringUtils in Apache commons.lang has a method for getting the Levenshtein distance of two strings.

Upvotes: 1

Related Questions