共同学习Java源码--常用数据类型--String(六)

来源:互联网 发布:网络强国与青年运动 编辑:程序博客网 时间:2024/06/09 20:22
    public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true
                : (anotherString != null)
                && (anotherString.value.length == value.length)
                && regionMatches(true, 0, anotherString, 0, value.length);

    }

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;
    }



这也是个非常常用且重要的方法,判断字符串是否值相等,且忽略大小写。

首先一个三目运算符判断和输入参数是否为同一对象,是的话继续向&&右执行,否的话,接着判断参数是否不为空如果不为空,则继续向&&右执行,如果为空则直接返回false。

第二个表达式判断两个字符串的长度是否相等。

第三个表达式调用了下面那个方法,传入的第一个参数为true也就是忽略大小写,第二个参数为本类对象的下标toffset,第三个参数是要判断是否值相等的字符串,第四个参数为参数字符串的下标ooffset,第五个参数为两个字符串共同的长度。

这个方法先用四个临时变量接收两个字符串的char数组value和各自开始下标toffset和ooffset,然后判断这些下标是否小于0或是否大于各自value的总长度减去第五个参数,也就是判断是否会下标越界。

然后获取每个value数组的元素,逐一进行判断,如果相等直接跳出本次循环。如果忽略大小写,则全部转换成大写再判断是否相等,相等就跳出循环。如果不忽略大小写,则不进行转换成大写后的判断。

这里的注释说了,转换成大写的方法不能正常运转,对于大小写规则奇怪的格鲁吉亚字母,还要最后进行一次判断,将各自的value数组元素同时转换成小写判断一次。

0 0
原创粉丝点击