Reputation: 3906
I would like to compare two strings and get some score how much these look alike. For example "The sentence is almost similar" and "The sentence is similar".
I'm not familiar with existing methods in Java, but for PHP I know the levenshtein function.
Are there better methods in Java?
Upvotes: 44
Views: 44737
Reputation: 4749
The following Java libraries offer multiple compare algorithms (Levenshtein, Jaro Winkler, ...):
Both libraries have a Java documentation (Apache Commons Lang Javadoc,Simmetrics Javadoc).
//Usage of Apache Commons Text
import org.apache.commons.text.similarity.JaroWinklerDistance;
public double compareStrings(String stringA, String stringB) {
return new JaroWinklerDistance().apply(stringA, stringB);
}
//Usage of Simmetrics
import uk.ac.shef.wit.simmetrics.similaritymetrics.JaroWinkler
public double compareStrings(String stringA, String stringB) {
JaroWinkler algorithm = new JaroWinkler();
return algorithm.getSimilarity(stringA, stringB);
}
Upvotes: 60
Reputation: 21
Shameless plug, but I wrote a library also:
https://github.com/vickumar1981/stringdistance
It has all these functions, plus a few for phonetic similarity (if one word "sounds like" another word - returns either true or false unlike the other fuzzy similarities which are numbers between 0-1).
Also includes dna sequencing algorithms like Smith-Waterman and Needleman-Wunsch which are generalized versions of Levenshtein.
I plan, in the near future, on making this work with any array and not just strings (an array of characters).
Upvotes: 2
Reputation: 199
You can find implementations of Levenshtein and other string similarity/distance measures on https://github.com/tdebatty/java-string-similarity
If your project uses maven, installation is as simple as
<dependency>
<groupId>info.debatty</groupId>
<artifactId>java-string-similarity</artifactId>
<version>RELEASE</version>
</dependency>
Then, to use Levenshtein for example
import info.debatty.java.stringsimilarity.*;
public class MyApp {
public static void main (String[] args) {
Levenshtein l = new Levenshtein();
System.out.println(l.distance("My string", "My $tring"));
System.out.println(l.distance("My string", "My $tring"));
System.out.println(l.distance("My string", "My $tring"));
}
}
Upvotes: 3
Reputation: 354774
The Levensthein distance is a measure for how similar strings are. Or, more precisely, how many alterations have to be made that they are the same.
The algorithm is available in pseudo-code on Wikipedia. Converting that to Java shouldn't be much of a problem, but it's not built-in into the base class library.
Wikipedia has some more algorithms that measure similarity of strings.
Upvotes: 21
Reputation: 51924
yeah thats a good metric, you could use StringUtil.getLevenshteinDistance() from apache commons
Upvotes: 16