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 ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.