Reputation: 289
Is there a method to compare two String
values like .compareTo
but that returns the number of letters that aren't the same?
Example:
"SomeString".anotherCompareTo("SomeStrng") -> 1
"SomeString".anotherCompareTo("SmeStrng") -> 2
"SomeString".anotherCompareTo("SomeStrong") -> 1
I can't find anything. I tried to convert it to charArrays and write a method myself but failed. If this is not possible, maybe there's a method that compares two strings with the same length that returns the number of "mistakes"?
Upvotes: 1
Views: 109
Reputation: 9041
Java's String.replaceAll()
seems to do what you're wanting. The first parameter being a regex pattern, so you're asking to replace all characters in the pattern with an empty string leaving the characters that don't match the pattern.
public static void main(String[] args) {
String s1 = "SomeString";
String s2 = "SomeStrng";
String s3 = "SmeStrng";
String s4 = "SomeStrong";
String result = s1.replaceAll("[" + s2 + "]", "");
System.out.println(result + ": " + result.length());
result = s1.replaceAll("[" + s3 + "]", "");
System.out.println(result + ": " + result.length());
result = s1.replaceAll("[" + s4 + "]", "");
System.out.println(result + ": " + result.length());
}
Results:
i: 1
oi: 2
i: 1
Upvotes: 1
Reputation: 38531
Apache Commons has a method to diff Strings
StringUtils.difference(String str1, String str2)
that you can use to create a method that returns the number of differences very easily.
Edit:
Infact it already exists:
StringUtils.getLevenshteinDistance(String str1, String str2)
Upvotes: 5