找出两个字符串之间的区别

时间:2012-08-23 06:40:29

标签: java string comparison

假设我有两个长字符串。它们几乎相同。

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

以上代码仅供参考。实际字符串很长。

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

我如何检查这两个角色是哪个?

9 个答案:

答案 0 :(得分:24)

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

答案 1 :(得分:13)

如果没有遍历字符串,你只能知道 它们是不同的,而不是 where - 并且只有它们的长度不同。如果你真的需要知道不同的字符是什么,你必须串联两个字符串并比较相应位置的字符。

答案 2 :(得分:5)

以下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 + ")";
        }
    }
}

答案 3 :(得分:1)

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

答案 4 :(得分: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而不是union中删除交集来完成。

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

答案 5 :(得分: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相关的工具。

答案 6 :(得分:1)

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在我的眼中燃烧:-)) 仍然可以。对于使用长而复杂的字符串的人来说,它可能是一个有价值的工具。

答案 7 :(得分: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]]]

答案 8 :(得分:0)

你可以试试这个

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

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

System.out.print(now);      
//ans=le