30

2つの長い文字列があるとします。それらはほとんど同じです。

String a = "this is a example"
String b = "this is a examp"

上記のコードはほんの一例です。実際の文字列はかなり長いです。

問題は、一方の文字列がもう一方の文字列より2文字多いことです。

これらの2つのキャラクターがどちらであるかを確認するにはどうすればよいですか?

4

11 に答える 11

36

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;
}
于 2012-08-23T10:27:56.317 に答える
19

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"

参照: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

于 2015-04-29T19:30:13.573 に答える
13

文字列を反復処理しなくても、文字列が異なることだけを知ることができます。どこにあるかはわかりません。また、文字列の長さが異なる場合にのみわかります。異なる文字が何であるかを本当に知る必要がある場合は、両方の文字列をタンデムでステップスルーし、対応する場所で文字を比較する必要があります。

于 2012-08-23T06:42:53.180 に答える
2
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;
    }
}
于 2012-08-23T11:55:31.820 に答える
-1

あなたはこれを試すことができます

String a = "this is a example";
String b = "this is a examp";

String ans= a.replace(b, "");

System.out.print(now);      
//ans=le
于 2021-06-21T14:13:59.487 に答える