查找两个字符串之间的差异 [英] Find difference between two Strings

查看:135
本文介绍了查找两个字符串之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

Problem is one string have 2 more characters than the other.

如何检查哪两个字符?

How can I check which are those two character?

推荐答案

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

这篇关于查找两个字符串之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆