JDK源码之lang.String(四)String类中的常用方法

本文详细介绍了Java中String类的多种方法,包括regionMatches、startsWith、endsWith、hashCode及indexOf系列方法的功能、参数与使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.String类中的regionMatches(int toffset, String other, int ooffset,int len)方法:

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

测试两个字符串区域是否相等。

这个String对象的子字符串与其他参数的子字符串进行比较。 如果这些子串表示相同的字符序列,结果是真的。 要比较的String对象的子String从索引toffset开始,长度为len 。 其他要比较的ooffset始于索引ooffset ,长度为len 。 结果是false当且仅当以下至少有一个是真的:

    • toffset为负数。
    • ooffset是否定的。
    • toffset+len大于此String对象的长度。
    • ooffset+len大于另一个参数的长度。
    • 有一些非负整数k小于len ,使得: this.charAt(toffset + k ) != other.charAt(ooffset + k )

 

2.String类中的regionMatches(boolean ignoreCase, int toffset,String other, int ooffset, int len)方法:

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

该方法和上一个方法基本相同,区别是该方法可区分大写字母和小写字母,如果在 boolean ignoreCase处写 true,表示将不区分大小写,写false则表示将区分大小写。

 

3.String类中的startsWith(String prefix, int toffset)方法:

public boolean startsWith(String prefix, int toffset) {
        char ta[] = value;
        int to = toffset;
        char pa[] = prefix.value;
        int po = 0;
        int pc = prefix.value.length;
        // Note: toffset might be near -1>>>1.
        if ((toffset < 0) || (toffset > value.length - pc)) {
            return false;
        }
        while (--pc >= 0) {
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }

测试在指定索引处开始的此字符串的子字符串是否以指定的前缀开头。

prefix - 前缀。

toffset - 在哪里开始查找这个字符串。

true如果由参数表示的字符序列是从索引toffset开始的此对象的子字符串的前缀; false否则。 如果toffset为负数或大于此String对象的长度,则结果为false ; 否则结果与表达式的结果相同

示例:

package com.ftl814;

public class Test {

	public static void main(String[] args) {
		String str="abcdefg";
		
		System.out.println(str.startsWith("cd", 2));
		System.out.println(str.startsWith("co", 2));
		
	}
}

输出:

 

4.String类中的startsWith(String prefix)方法:

    public boolean startsWith(String prefix) {
        return startsWith(prefix, 0);
    }

测试此字符串是否以指定的前缀开头。

prefix - 前缀。

示例:

package com.ftl814;

public class Test {

	public static void main(String[] args) {
		String str="abcdefg";
		
		System.out.println(str.startsWith("cd"));
		System.out.println(str.startsWith("ab"));
		
	}
}

输出:

 

5.String类中的endsWith(String suffix)方法:

    public boolean endsWith(String suffix) {
        return startsWith(suffix, value.length - suffix.value.length);
    }

 测试此字符串是否以指定的后缀结尾。

与startsWith(String prefix)方法一样,一个判断的是前缀,一个判断的是后缀。

 

6.String类中的hashCode()方法

    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

 返回此字符串的哈希码。 String对象的哈希代码计算为:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

使用int算术,其中s[i]是字符串的第i个字符, n是字符串的长度, ^表示取幂。 (空字符串的哈希值为零)

示例:

package com.ftl814;

public class Test {

	public static void main(String[] args) {
		String str1="";
		String str2="12";
		System.out.println(str1.hashCode());
		System.out.println(str2.hashCode());
		
	}
}

 输出:

解析:‘1’对应的asc||码是49,‘2’对应的asc||码是50,所以hashcode的值是49*31^1+50*31^0=1569

 

7.String类中的indexOfSupplementary(int ch, int fromIndex)方法:

    private int indexOfSupplementary(int ch, int fromIndex) {
        if (Character.isValidCodePoint(ch)) {
            final char[] value = this.value;
            final char hi = Character.highSurrogate(ch);
            final char lo = Character.lowSurrogate(ch);
            final int max = value.length - 1;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == hi && value[i + 1] == lo) {
                    return i;
                }
            }
        }
        return -1;
    }

 处理(罕见的)带有补充字符的indexOf调用。

 

8.String类中的indexOf(int ch)方法:

 public int indexOf(int ch) {
        return indexOf(ch, 0);
    }

返回指定字符第一次出现的字符串内的索引。

如果与值的字符ch在此表示的字符序列发生String第一事件发生之对象,则索引(在Unicode代码单元)被返回。

对于从0到0xFFFF(含)范围内的ch的值,这是最小值k ,使得: this.charAt(k) == ch 是真的。

对于ch其他值,它是最小值k ,使得: this.codePointAt(k) == ch是真的。

在这两种情况下,如果此字符串中没有此类字符,则返回-1

 

9.String类中的indexOf(int ch, int fromIndex)方法:

public int indexOf(int ch, int fromIndex) {
        final int max = value.length;
        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= max) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return indexOfSupplementary(ch, fromIndex);
        }
    }

 

10.String类中的indexOf(String str)方法:

    public int indexOf(String str) {
        return indexOf(str, 0);
    }

11.String类中的indexOf(String str, int fromIndex)方法:

    public int indexOf(String str, int fromIndex) {
        return indexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }

 

12.String类中的indexOf(char[] source, int sourceOffset, int sourceCount,String target, int fromIndex)方法:

    static int indexOf(char[] source, int sourceOffset, int sourceCount,
            String target, int fromIndex) {
        return indexOf(source, sourceOffset, sourceCount,
                       target.value, 0, target.value.length,
                       fromIndex);
    }

 

 

13.String类中的indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex)方法:

 static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值