String类的substring方法

想必做java开发的同学对substring方法都不陌生,那么他是如何实现的呢?如果让你自己去实现,你会怎么做?我们一块去看下源码实现

public String substring(int beginIndex, int endIndex) {
       //起始位置小于0抛字符串越界异常
        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这个构造函数

public String(char value[], int offset, int count) {
        //value对应空字符数组,offset对应截取起始位置,cout代表新生成 
        //字符串的长度
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= value.length) {
                this.value = "".value;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

copyOfRange方法的作用就是复制源数组生成新的数组,要复制的源数组为value,复制的起始位置为offset,复制的结束位置为offset+count,可以看这个示例

public static  void main(String [] args){
        String [] elementArray={"0","1","2","3"};
        String [] newArray = Arrays.copyOfRange(elementArray,1,3);
        for(String elem:newArray){
            System.out.println(elem);
        }

运行结果为

1
2

Process finished with exit code 0

 

你想拥有什么,你就去追求什么!
原文地址:https://www.cnblogs.com/lchzlp/p/13090132.html