zoukankan      html  css  js  c++  java
  • 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

     

    你想拥有什么,你就去追求什么!
  • 相关阅读:
    20155209林虹宇虚拟机的安装及一点Linux的学习
    预备作业2林虹宇20155209
    预备作业01:你期望的师生关系是什么?
    20155203
    我眼中的师生关系以及对于专业学习的展望
    20155319的第一次随笔
    20155336 2016-2017-2《JAVA程序设计》第二周学习总结
    20155336 2016-2017-2《JAVA程序设计》第一周学习总结
    虎光元的第三次随笔
    20155336虎光元
  • 原文地址:https://www.cnblogs.com/lchzlp/p/13090132.html
Copyright © 2011-2022 走看看