查找两个字符串之间的差异

问题描述 投票:20回答:9

假设我有两个长字符串。他们几乎一样。

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

上面的代码只是举例。实际的字符串很长。

问题是一个字符串比另一个字符串具有2个更多字符

我如何检查这两个字符是哪个?

java string comparison
9个回答
26
投票

您可以使用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;
}

14
投票

要找到2个字符串之间的差异,可以使用StringUtils类和difference方法。它比较两个字符串,并返回它们不同的部分。

 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


13
投票

没有遍历字符串,您只能知道that是不同的,而不是where-并且只有它们的长度不同。如果确实需要知道不同的字符是什么,则必须一前一后地遍历两个字符串,然后在相应位置比较字符。


7
投票

以下Java代码段有效地计算了必须从各个字符串中删除(或添加到各个字符串)的最小字符集,以使字符串相等。这是动态编程的一个示例。

import java.util.HashMap;
import java.util.Map;

public class StringUtils {

    /**
     * Examples
     */
    public static void main(String[] args) {
        System.out.println(diff("this is a example", "this is a examp")); // prints (le,)
        System.out.println(diff("Honda", "Hyundai")); // prints (o,yui)
        System.out.println(diff("Toyota", "Coyote")); // prints (Ta,Ce)
        System.out.println(diff("Flomax", "Volmax")); // prints (Fo,Vo)
    }

    /**
     * Returns a minimal set of characters that have to be removed from (or added to) the respective
     * strings to make the strings equal.
     */
    public static Pair<String> diff(String a, String b) {
        return diffHelper(a, b, new HashMap<>());
    }

    /**
     * Recursively compute a minimal set of characters while remembering already computed substrings.
     * Runs in O(n^2).
     */
    private static Pair<String> diffHelper(String a, String b, Map<Long, Pair<String>> lookup) {
        long key = ((long) a.length()) << 32 | b.length();
        if (!lookup.containsKey(key)) {
            Pair<String> value;
            if (a.isEmpty() || b.isEmpty()) {
                value = new Pair<>(a, b);
            } else if (a.charAt(0) == b.charAt(0)) {
                value = diffHelper(a.substring(1), b.substring(1), lookup);
            } else {
                Pair<String> aa = diffHelper(a.substring(1), b, lookup);
                Pair<String> bb = diffHelper(a, b.substring(1), lookup);
                if (aa.first.length() + aa.second.length() < bb.first.length() + bb.second.length()) {
                    value = new Pair<>(a.charAt(0) + aa.first, aa.second);
                } else {
                    value = new Pair<>(bb.first, b.charAt(0) + bb.second);
                }
            }
            lookup.put(key, value);
        }
        return lookup.get(key);
    }

    public static class Pair<T> {
        public Pair(T first, T second) {
            this.first = first;
            this.second = second;
        }

        public final T first, second;

        public String toString() {
            return "(" + first + "," + second + ")";
        }
    }
}

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;
    }
}

1
投票

要查找两行中不同的单词,可以使用以下代码。

    String[] strList1 = str1.split(" ");
    String[] strList2 = str2.split(" ");

    List<String> list1 = Arrays.asList(strList1);
    List<String> list2 = Arrays.asList(strList2);

    // Prepare a union
    List<String> union = new ArrayList<>(list1);
    union.addAll(list2);

    // Prepare an intersection
    List<String> intersection = new ArrayList<>(list1);
    intersection.retainAll(list2);

    // Subtract the intersection from the union
    union.removeAll(intersection);

    for (String s : union) {
        System.out.println(s);
    }

最后,您将获得一个在两个列表中都不同的单词列表。可以轻松地对其进行修改,使其仅在第一个列表或第二个列表中包含不同的单词,而不会同时出现。这可以通过仅从list1或list2而不是联合中删除交集来完成。

可以通过将拆分列表中每个单词的长度加起来(以及拆分正则表达式)或简单地执行String.indexOf(“ subStr”)来计算确切位置。


1
投票

要直接获得更改的部分,而不仅仅是结束部分,可以使用Google的Diff Match Patch

List<Diff> diffs = new DiffMatchPatch().diffMain("stringend", "stringdiffend");
  for (Diff diff : diffs) {
    if (diff.operation == Operation.INSERT) {
      return diff.text; // Return only single diff, can also find multiple based on use case
    }
  }
}

要在Android中添加:implementation 'org.bitbucket.cowwoc:diff-match-patch:1.2'

此软件包比该功能强大得多,它主要用于创建与diff相关的工具。


0
投票

用于发现字符串之间差异的另一个很棒的库是https://github.com/java-diff-utils的DiffUtils。我用了德米特里·瑙缅科的叉子:

public void testDiffChange() {
    final List<String> changeTestFrom = Arrays.asList("aaa", "bbb", "ccc");
    final List<String> changeTestTo = Arrays.asList("aaa", "zzz", "ccc");
    System.out.println("changeTestFrom=" + changeTestFrom);
    System.out.println("changeTestTo=" + changeTestTo);
    final Patch<String> patch0 = DiffUtils.diff(changeTestFrom, changeTestTo);
    System.out.println("patch=" + Arrays.toString(patch0.getDeltas().toArray()));

    String original = "abcdefghijk";
    String badCopy =  "abmdefghink";
    List<Character> originalList = original
            .chars() // Convert to an IntStream
            .mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
            .collect(Collectors.toList()); // Collect in a List<Character>
    List<Character> badCopyList = badCopy.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
    System.out.println("original=" + original);
    System.out.println("badCopy=" + badCopy);
    final Patch<Character> patch = DiffUtils.diff(originalList, badCopyList);
    System.out.println("patch=" + Arrays.toString(patch.getDeltas().toArray()));
}

结果准确显示了更改的位置(基于零的计数):

changeTestFrom=[aaa, bbb, ccc]
changeTestTo=[aaa, zzz, ccc]
patch=[[ChangeDelta, position: 1, lines: [bbb] to [zzz]]]
original=abcdefghijk
badCopy=abmdefghink
patch=[[ChangeDelta, position: 2, lines: [c] to [m]], [ChangeDelta, position: 9, lines: [j] to [n]]]

0
投票

Google的Diff Match Patch很好,但是要安装到我的Java maven项目中却很痛苦。仅仅添加一个Maven依赖项是行不通的。 eclipse刚刚创建了目录,并添加了lastUpdated信息文件。最后,在第三次尝试中,我将以下内容添加到了pom中:

<dependency>
    <groupId>fun.mike</groupId>
     <artifactId>diff-match-patch</artifactId>
    <version>0.0.2</version>
</dependency>

然后我从https://search.maven.org/search?q=g:fun.mike%20AND%20a:diff-match-patch%20AND%20v:0.0.2手动将jar和源jar文件放入.m2存储库中>

毕竟,以下代码有效:

import fun.mike.dmp.Diff;
import fun.mike.dmp.DiffMatchPatch;

DiffMatchPatch dmp = new DiffMatchPatch();
LinkedList<Diff> diffs = dmp.diff_main("Hello World.", "Goodbye World.");
System.out.println(diffs);

结果:

[Diff(DELETE,"Hell"), Diff(INSERT,"G"), Diff(EQUAL,"o"), Diff(INSERT,"odbye"), Diff(EQUAL," World.")]

显然,这不是最初写(或什至完全移植)到Java中的。 (diff_main?我可以感觉到C在我的眼中燃烧:-))仍然可以。对于使用长而复杂的字符串的人来说,它可能是一个有价值的工具。

© www.soinside.com 2019 - 2024. All rights reserved.