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.

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

def hamming(s1 ,s2)

dist = 0

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

dist

end

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(s1.at(k) != s2.at(k)) ++counter; return counter; }

But that's a tad ugly.

As ugly as it may look, that’s the standard for Java. A quick Google code search only pulls up things similar to what you have.

There is a blog:

https://blogs.ucl.ac.uk/chime/2010/06/28/java-example-code-of-common-similarity-algorithms-used-in-data-mining/

And the project contains other distances: http://alias-i.com/lingpipe/index.html

Odd:) I’m tring to apply distance to compression