String中的equalsIgnoreCase方法与regionMatches方法解析

时间:2025-02-15 14:14:46

equalsIgnoreCase方法的作用是,比较两个字符串,不区分大小写。
与CompareToIgnoreCase的区别在于,equalsIgnoreCase的返回值是boolean,而CompareToIgnoreCase的返回值是int。

下面我们来看一下equalsIgnoreCase()方法的源码

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

如果两个字符串在常量池之中有相同对象的话,直接返回true,如果不相等,还要判断,anotherString是否为null,二者长度比较的返回值,和regionMatches()方法的返回值共同判断。
下面我们来看一下regionMatches()这个方法的源码。

 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 = (c1);
                char u2 = (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 ((u1) == (u2)) {
                    continue;
                }
            }
            return false;
        }
        return true;
    }

这个方法 的作用是测试两个字符串区域是否相等。
这个方法还有一个重载方法。

   public boolean regionMatches(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) {
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }

这两个方法的区别在于第一个方法的参数列表多了一个boolean类型的参数,这个参数的作用是,如果为true,区分大小写,如果为false,就不区分大小写。