Computing the Hamming distance between two strings in Java?

Odd. I was looking this morning for some Java code to compute the Hamming distance between any two strings in Java, and could not find it. There are plenty of code samples for the Hamming distance between integers, but I am really looking for something that can process String objects.

Anyone knows where I could find this?

Update. Yes, I know it is not difficult. I am really looking for a Java two-liner.

4 thoughts on “Computing the Hamming distance between two strings in Java?”

  1. It’s very easy to compute — it’s just the number of differences, right?

    def hamming(s1 ,s2)
    dist = 0,s1.length-1).each {|i| dist += 1 unless s1[i] == s2[i] }

  2. Right.

    I got as far as this:

    int hamming (String s1, String s2) {
    if(s1.size() != s2.size()) return -1;// not sure whether there is someting better to do
    int counter = 0;
    for (int k = 0; k < s1.size();++k) if( != ++counter; return counter; }

    But that's a tad ugly.

Leave a Reply

Your email address will not be published. Required fields are marked *