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

     

    你想拥有什么,你就去追求什么!
  • 相关阅读:
    安装虚拟环境virtualenv
    安装python3、ipython、jupyter
    配置yum源
    面向对象
    sqrt开平方算法的尝试,是的看了卡马克大叔的代码,我来试试用C#写个0x5f3759df和0x5f375a86跟System.Math.Sqrt到底哪个更强
    python开发环境
    phthon中的open函数模式
    picoscope 动态链接库调用位置确定,可进行图标编辑
    设计模式笔记(2)-工厂模式
    设计模式笔记(1)-单体模式
  • 原文地址:https://www.cnblogs.com/lchzlp/p/13090132.html
Copyright © 2011-2022 走看看