共同学习Java源代码--常用工具类--AbstractStringBuilder(六)

本文详细介绍了StringBuilder类中的几个关键方法:删除指定位置字符、替换指定区间字符串及截取子串的方法实现。通过源码分析,展示了如何进行字符串的修改与提取,并解释了内部的工作原理。

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

    public AbstractStringBuilder deleteCharAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        System.arraycopy(value, index+1, value, index, count-index-1);
        count--;
        return this;

    }

这个方法是删除指定下标的字符。

先判断下标是否越界,否则抛异常。

然后将下标之后的元素拷贝到下标处,count自减一。最后返回本对象。

    public AbstractStringBuilder replace(int start, int end, String str) {
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (start > count)
            throw new StringIndexOutOfBoundsException("start > length()");
        if (start > end)
            throw new StringIndexOutOfBoundsException("start > end");


        if (end > count)
            end = count;
        int len = str.length();
        int newCount = count + len - (end - start);
        ensureCapacityInternal(newCount);


        System.arraycopy(value, end, value, start + len, count - end);
        str.getChars(value, start);
        count = newCount;
        return this;
    }

这个方法是将一个字符串镶嵌在本对象中。

先给value扩容,扩大的容量就是两个字符串之和减去下标之差。

然后将end下标之后的字符复制到start+len下标之后,这样start和end之间就有了len长度的空白,然后将参数填充进去。

最后返回本对象。

    public String substring(int start) {
        return substring(start, count);
    }

    public CharSequence subSequence(int start, int end) {
        return substring(start, end);
    }

    public String substring(int start, int end) {
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (end > count)
            throw new StringIndexOutOfBoundsException(end);
        if (start > end)
            throw new StringIndexOutOfBoundsException(end - start);
        return new String(value, start, end - start);
    }

这三个方法一起看,就是截取字符串。这里是返回新字符串。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值