/** * Tests if the substring of this string beginning at the * specified index starts with the specified prefix. * * @param prefix the prefix. * @param toffset where to begin looking in this string. * @return {@code true} if the character sequence represented by the * argument is a prefix of the substring of this object starting * at index {@code toffset}; {@code false} otherwise. * The result is {@code false} if {@code toffset} is * negative or greater than the length of this * {@code String} object; otherwise the result is the same * as the result of the expression * <pre> * this.substring(toffset).startsWith(prefix) * </pre> */ 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; } /** * Tests if this string starts with the specified prefix. * * @param prefix the prefix. * @return {@code true} if the character sequence represented by the * argument is a prefix of the character sequence represented by * this string; {@code false} otherwise. * Note also that {@code true} will be returned if the * argument is an empty string or is equal to this * {@code String} object as determined by the * {@link #equals(Object)} method. * @since 1. 0 */ public boolean startsWith(String prefix) { return startsWith(prefix, 0); }
可以看到,两个版本的用法仅仅是在有无传入 toffest 这个参数上,或者说传入的 toffest 是否为 0
所以我们只需要弄明白第一个有 toffest 的版本就能理解这个方法
解读这个方法:
1.value 是String对象的值,也就是我们对象本身所携带值,使用了一个 char[] 来接收这个值便于后续的使用
2.to 记录 偏移量 或者说是 往后要对比的字符个数
3.使用了 char[] pa 来接收我们传入的字符串的值便于后续使用
4.po 作为一个遍历的下标
5.比对个数不可能为零,且比对的个数不能比 被比字符串字符数-比对字符串的字符数 多 (toffest + pc > value.length)=>发生越界
if ((toffset < 0) || (toffset > value.length - pc)) { return false; }
6.从 被比字符串 的第 to 个(也就是第 toffest个) 和 pa 的第 po 个(也就是比对字符串 prefix 的第0个)做比较;同时对比的次数 -1
while (--pc >= 0) { if (ta[to++] != pa[po++]) { return false; } }
标签:startsWith,code,return,String,value,prefix,源码,toffset From: https://www.cnblogs.com/xxaxf/p/18156239