difference()
is a static method of the StringUtils
that is used to compare two strings and return the remaining characters of the second string that differ from the first string.
The comparison is case-sensitive in nature.
StringUtils
StringUtils
is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the StringUtils
class as follows:
import org.apache.commons.lang3.StringUtils;
public static String difference(final String str1, final String str2)
The function takes on the following parameters:
final String str1
: the first string.final String str2
: the second string.This method returns the remaining characters of the second string from the position where it differs from the first string.
First string - "educative"
Second string - "educative.io"
The method returns .io
, indicating the remaining characters of the second string after the point of difference from the first string.
First string - "educative.io"
Second string - "educative"
The method returns an empty string, indicating that the second string does not have characters from the position of the difference with the first string.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {String s1 = "educative";String s2 = "educative.io";System.out.printf("Difference between \"%s\" & \"%s\" - \"%s\"", s1, s2, StringUtils.difference(s1,s2));System.out.println();s1 = "educative.io";s2 = "educative";System.out.printf("Difference between \"%s\" & \"%s\" - \"%s\"", s1, s2, StringUtils.difference(s1,s2));}}
The output of the code will be as follows:
Difference between "educative" & "educative.io" - ".io"
Difference between "educative.io" & "educative" - ""