Home > Net >  Counting differences in 2 strings which have the same length
Counting differences in 2 strings which have the same length

Time:01-07

Let's say I have two strings with the same character length. They look something like this.

String s1 = "R20k20r20";
String s2 = "R21k20r20";

I don't really care about where the differences are, but I want to be able to count how many differences they have between them. In this case, it should be just 1. What would be the easiest way to accomplish this given the circumstances?

CodePudding user response:

You could iterate up to the length of the strings and increment a counter for each different character:

int numDiffs = 0;
for (int i = 0; i < s1.length();   i) {
    if (s1.charAt(i) != s2.charAt(i)) {
          numDiffs;
    }
}

Or you could stream this length for an arguably more elegant one-liner:

long numDiffs = 
    IntStream.range(0, s1.length()).filter(i -> s1.charAt(i) != s2.charAt(i)).count();
  • Related