String的部分源码分析(substring、startsWith、endsWith)(一)

1.String的substring方法源码:

       public String substring(int beginIndex) {

//判断开始位置是否小于0
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }


        int subLen = value.length - beginIndex;

//判断开始位置是否超出该字符串长度
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }

//如果开始位置为0,则截取的字符串和原字符串为同一字符串;否则将通过String构造方法,传递字符串,开始位置和截取长度获取字符串
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }

  public String(char value[], int offset, int count) {

//判断开始位置是否小于0
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }

//判断开始位置是否小于0
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // Note: offset or count might be near -1>>>1.

//判断是否满足条件
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }

//通过copyOfRange方法,传递字符串数组,开始位置和结束位置获取字符串
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

  public static char[] copyOfRange(char[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        char[] copy = new char[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

2.String的startsWith方法源码:

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;
        //判断比较的起始点是否小于0或者起始点的开始位置无法将比较字符串比较完
        if ((toffset < 0) || (toffset > value.length - pc)) {
            return false;

        }

//循环比进行对比较字符串数组的字符一个一个比较是否相等

        while (--pc >= 0) {

//被比较字符串的从起始点开始与比较字符串数组一一比较

            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;

    }


3.String的endsWith方法源码:

public boolean endsWith(String suffix) {

//巧妙的使用了startsWith方法,计算出比较的开始位置(被比较串长度-去比较的串长度)
        return startsWith(suffix, value.length - suffix.value.length);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值