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

新手上路,请多包涵

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

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

以上代码仅作为示例。实际字符串很长。

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

我怎样才能检查这两个字符是哪一个?

原文由 user17526 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 570
1 个回答

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

原文由 JRL 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题