码迷,mamicode.com
首页 > 其他好文 > 详细

JDK1.8的String详解

时间:2020-06-11 14:58:55      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:his   复制   inf   loading   lazy   har   bounds   --   字符串   

1.String.substring()方法

substring(beginIndex,endIndex) 方法返回字符串的子字符串。

  • beginIndex -- 起始索引(包括), 索引从 0 开始。

  • endIndex -- 结束索引(不包括)。

再JDK1.7+中实际是重新创建了一个字符数组

技术图片

String.substring()有两个方法

技术图片

实现方法

判断beginIndex和endIndex是否合法,否则抛出异常

通过new String(value, beginIndex, subLen)方法复制字符串

 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);
    }

 

 this.value = Arrays.copyOfRange(value, offset, offset+count);

复制一个数组从offsetoffset+count

public String(char value[], int offset, int count) {
        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);
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

JDK1.8的String详解

标签:his   复制   inf   loading   lazy   har   bounds   --   字符串   

原文地址:https://www.cnblogs.com/asndxj/p/13093213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!