Java 不区分大小写比较字符串

作者: adm 分类: java 发布时间: 2022-11-18

比较字符串时使用:equalsIgnoreCase()

String.equals()对大小写敏感,

而String.equalsIgnoreCase()忽略大小写

例如:

"ABC".equals("abc")是false

"ABC".equalsIgnoreCase("abc")为ture

源码:

 
    public boolean equalsIgnoreCase(String anotherString) {
        final int len = length();
        return (this == anotherString) ? true
                : (anotherString != null)
                && (anotherString.length() == len)
                && regionMatches(true, 0, anotherString, 0, len);
    }
 
    public boolean regionMatches(boolean ignoreCase, int toffset,
            String other, int ooffset, int len) {
        int to = toffset;
        int po = ooffset;
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0)
                || (toffset > (long)length() - len)
                || (ooffset > (long)other.length() - len)) {
            return false;
        }
        while (len-- > 0) {
            char c1 = charAt(to++);
            char c2 = other.charAt(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;
    }

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!