2つの長い文字列があるとします。それらはほとんど同じです。
String a = "this is a example"
String b = "this is a examp"
上記のコードはほんの一例です。実際の文字列はかなり長いです。
問題は、一方の文字列がもう一方の文字列より2文字多いことです。
これらの2つのキャラクターがどちらであるかを確認するにはどうすればよいですか?
2つの長い文字列があるとします。それらはほとんど同じです。
String a = "this is a example"
String b = "this is a examp"
上記のコードはほんの一例です。実際の文字列はかなり長いです。
問題は、一方の文字列がもう一方の文字列より2文字多いことです。
これらの2つのキャラクターがどちらであるかを確認するにはどうすればよいですか?
StringUtils.difference(String first、String second)を使用できます。
これは彼らがそれを実装した方法です:
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;
}
2 つの文字列の違いを見つけるには、StringUtilsクラスとdifferenceメソッドを使用できます。2 つの文字列を比較し、異なる部分を返します。
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"
文字列を反復処理しなくても、文字列が異なることだけを知ることができます。どこにあるかはわかりません。また、文字列の長さが異なる場合にのみわかります。異なる文字が何であるかを本当に知る必要がある場合は、両方の文字列をタンデムでステップスルーし、対応する場所で文字を比較する必要があります。
String strDiffChop(String s1, String s2) {
if (s1.length > s2.length) {
return s1.substring(s2.length - 1);
} else if (s2.length > s1.length) {
return s2.substring(s1.length - 1);
} else {
return null;
}
}
あなたはこれを試すことができます
String a = "this is a example";
String b = "this is a examp";
String ans= a.replace(b, "");
System.out.print(now);
//ans=le