2.14. Calculating String Difference
Problem
Your application needs to compare two strings and print out the difference.
Solution
Use StringUtils.difference( ),
StringUtils.indexOfDifference( ), and
StringUtils.getLevenshteinDistance( ).
StringUtils.difference( ) prints out the
difference between two strings,
StringUtils.indexOfDifference( ) returns the index
at which two strings begin to differ, and
StringUtils.getLevenshteinDistance( ) returns the
“edit distance” between two
strings. The following example demonstrates all three of these
methods:
int dist = StringUtils.getLevenshteinDistance( "Word", "World" ); String diff = StringUtils.difference( "Word", "World" ); int index = StringUtils.indexOfDifference( "Word", "World" ); System.out.println( "Edit Distance: " + dist ); System.out.println( "Difference: " + diff ); System.out.println( "Diff Index: " + index );
This code compares the strings “Word” and “World,” producing the following output:
Edit Distance: 2 Difference: ld Diff Index: 3
Discussion
StringUtils.difference()
returns the difference between two strings,
returning the portion of the second string, which starts to differ
from the first. StringUtils.indexOfDifference()
returns the index at which the second string starts to diverge from
the first. The difference between
“ABC” and
“ABE” is
“E,” and the index of the
difference is 2. Here’s a more complex example:
String a = "Strategy"; String b = "Strategic"; String difference = StringUtils.difference( a, b ); int differenceIndex ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access