Suppose I have two long strings. They are almost same.
String a = "this is a example" String b = "this is a examp"
Above code is just for example. Actual strings are quite long.
Problem is one string have 2 more characters than the other.
How can I check which are those two character?
Use the == and != operators to compare two strings for equality. Use the is operator to check if two strings are the same instance. Use the < , > , <= , and >= operators to compare strings alphabetically.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.
In SQL, we can compare two strings using STRCMP () function. STRCMP () returns '0' when the two strings are the same, returns '-1' if the first string is smaller than the second string, and returns 1 if the first string is larger than the second string.
You can use StringUtils.difference(String first, String second).
This is how they implemented it:
public static String difference(String str1, String str2) { if (str1 == null) { return str2; } if (str2 == null) { return str1; } int at = indexOfDifference(str1, str2); if (at == INDEX_NOT_FOUND) { return EMPTY; } return str2.substring(at); } public static int indexOfDifference(CharSequence cs1, CharSequence cs2) { if (cs1 == cs2) { return INDEX_NOT_FOUND; } if (cs1 == null || cs2 == null) { return 0; } int i; for (i = 0; i < cs1.length() && i < cs2.length(); ++i) { if (cs1.charAt(i) != cs2.charAt(i)) { break; } } if (i < cs2.length() || i < cs1.length()) { return i; } return INDEX_NOT_FOUND; }
To find the difference between 2 Strings you can use the StringUtils class and the difference method. It compares the two Strings, and returns the portion where they differ.
StringUtils.difference(null, null) = null StringUtils.difference("", "") = "" StringUtils.difference("", "abc") = "abc" StringUtils.difference("abc", "") = "" StringUtils.difference("abc", "abc") = "" StringUtils.difference("ab", "abxyz") = "xyz" StringUtils.difference("abcde", "abxyz") = "xyz" StringUtils.difference("abcde", "xyz") = "xyz"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With