关于String的substring(int beginIndex, int endIndex)

本文主要探讨了Java中String类的substring方法,指出其创建的是一个左闭右开的区间,并通过源码分析了其实现原理。文章还提及了substring方法在截取字符串时可能出现的异常情况,并对深拷贝和浅拷贝进行了简要讨论。
摘要由CSDN通过智能技术生成

问题描述

  • 今天刷leetcode的一道回文字符串的时候用到了,跳过去看源码的时候,想到自己之前用这个方法的时候,会认为能截到endIndex的位置,所以记录一下。

问题分析

  • 看String的源码咋说的
    在这里插入图片描述

  • 总的来说就是这是一个“左闭右开”区间, [beginIndex, endIndex)

    • 备注:beginIndex可以等于endIndex,这时候截到的是空字符串。

一些乱七八糟的东西

  • 整个方法

    /**
     * Returns a string that is a substring of this string. The
     * substring begins at the specified {@code beginIndex} and
     * extends to the character at index {@code endIndex - 1}.
     * Thus the length of the substring is {@code endIndex-beginIndex}.
     * <p>
     * Examples:
     * <blockquote><pre>
     * "hamburger".substring(4, 8) returns "urge"
     * "smiles".substring(1, 5) returns "mile"
     * </pre></blockquote>
     *
     * @param      beginIndex   the beginning index, inclusive.
     * @param      endIndex     the ending index, exclusive.
     * @return     the specified substring.
     * @exception  IndexOutOfBoundsException  if the
     *             {@code beginIndex} is negative, or
     *             {@code endIndex} is larger than the length of
     *             this {@code String} object, or
     *             {@code beginIndex} is larger than
     *             {@code endIndex}.
     */
    public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }
  • String的值,final,字符数组
    在这里插入图片描述
  • new String(value, beginIndex, subLen)构造函数,用的Arrays.copyOfRange(value, offset, offset+count)实现
  • 这个copy是深拷贝还是浅拷贝呢?
    • 老了,睡觉先,头发要紧。如果明天不偷懒的话可能会接着看,溜
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值