zoukankan      html  css  js  c++  java
  • work_09_JDK1.8的String详解

    1.String.substring()方法

    private final char value[];

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

     2.String.charAt()方法

    返回字符串指定索引处的字符

    public char charAt(int index) {
            if ((index < 0) || (index >= value.length)) {
                throw new StringIndexOutOfBoundsException(index);
            }
            return value[index];
        }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

  • 相关阅读:
    Codeforces Round #522(Div. 2) C.Playing Piano
    zstu月赛 招生
    Codeforces Round #519 D
    RMQ[区间最值查询] 算法
    Codeforces #364 (Div. 2) D. As Fa(数学公式推导 或者二分)
    尺取法
    Codeforces #366 (Div. 2) D. Ant Man (贪心)
    Codeforces #366 Div. 2 C. Thor (模拟
    裴蜀定理
    CF850 E. Random Elections
  • 原文地址:https://www.cnblogs.com/asndxj/p/13093213.html
Copyright © 2011-2022 走看看