为什么String.equalsIgnoreCase比较单个字符的高位和小写版本?

时间:2014-08-27 10:46:14

标签: java string comparison uppercase lowercase

我正在查看Java SE7 String类的解编译源代码,特别是在equalsIgnoreCase方法中,并且令我感到奇怪的是以下行(在while循环中执行,省略了本地变量):

if (((c1 = this.value[(o1++)]) != (c2 = target[(o2++)])) 
    && (toUpperCase(c1) != toUpperCase(c2)) 
    && (toLowerCase(c1) != toLowerCase(c2))) { 
        return false; 
}

我想知道为什么在大写和小写形式中检查c1和c2的不相等性。当然,如果大写的比较是相等的,那么甚至都不会达到小写......但是,我认为有时大写(c1)!=大写(c2)并且字符仍然相等比较小写。

建议任何人?

2 个答案:

答案 0 :(得分:3)

equalsIgnoreCase的真正Java源代码如下:

public boolean equalsIgnoreCase(String anotherString) {
    return (this == anotherString) ? true
            : (anotherString != null)
            && (anotherString.value.length == value.length)
            && regionMatches(true, 0, anotherString, 0, value.length);
}

您所谈论的代码位于regionMatches,此处是相关部分,并附有原始评论:

        if (ignoreCase) {
            // If characters don't match but case may be ignored
            // try converting both characters to uppercase.
            // If the results match, then the comparison scan should
            // continue.
            char u1 = Character.toUpperCase(c1);
            char u2 = Character.toUpperCase(c2);
            if (u1 == u2) {
                continue;
            }
            // Unfortunately, conversion to uppercase does not work properly
            // for the Georgian alphabet, which has strange rules about case
            // conversion.  So we need to make one last check before
            // exiting.
            if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
                continue;
            }
        }

课程:当实际源代码可以免费使用时,不要浪费时间查看反编译代码...就像Java库一样。实际上,只要我记得找到它,Java库的源代码就已包含在JDK中。

参考文献:

答案 1 :(得分:2)

this link开始,似乎存在一些上下框不匹配的Locales。使用的例子是土耳其语

if (x.toLowerCase().equals("list"))
对于x="LIST"

不会返回true。

我怀疑有几个这样的情况,因此选项要么指定似乎有可能产生许多其他打嗝的区域设置或比较两种情况。所以基本上有一些例子,在一种情况下字母可以是相同的而不是另一种