加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 找到两个字符串之间的区别

发布时间:2020-12-14 05:30:09 所属栏目:Java 来源:网络整理
导读:假设我有两个长串.他们几乎相同. String a = "this is a example"String b = "this is a examp" 以上代码就是例子.实际字符串相当长. 问题是一个字符串比另外两个字符多2个字符. 我该如何检查哪两个字符? 解决方法 您可以使用 StringUtils.difference(Strin
假设我有两个长串.他们几乎相同.
String a = "this is a example"
String b = "this is a examp"

以上代码就是例子.实际字符串相当长.

问题是一个字符串比另外两个字符多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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读