为什么equalsIgnoreCase()不只使用toLowerCase()?

时间:2018-08-14 09:31:23

标签: java

为什么equalsIgnoreCase()首先使用toUpperCase(),为什么toLowerCase()避免错误地识别格鲁吉亚字母,而不是第一次使用toLowerCase()而是仅使用它?

public boolean regionMatches(boolean ignoreCase, int toffset,
        String other, int ooffset, int len) {
    char ta[] = value;
    int to = toffset;
    char pa[] = other.value;
    int po = ooffset;
    // Note: toffset, ooffset, or len might be near -1>>>1.
    if ((ooffset < 0) || (toffset < 0)
            || (toffset > (long)value.length - len)
            || (ooffset > (long)other.value.length - len)) {
        return false;
    }
    while (len-- > 0) {
        char c1 = ta[to++];
        char c2 = pa[po++];
        if (c1 == c2) {
            continue;
        }
        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;
            }
        }
        return false;
    }
    return true;
}

1 个答案:

答案 0 :(得分:1)

请注意,它在toLowerCasetoUpperCaseu1)的结果上使用u2,而不是在原始字符({{ 1}}和c1)。检查的是c2转换为大写(c1),然后转换为小写匹配u1转换为大写(c2),然后转换为小写。因此,它不能只是跳过最初的u2,而是使用从中获得的信息(toUpperCaseu1)。