String类的subString(i)方法(基于jdk 1.9)

只有一个参数的;

String str = new String("ABCD");
System.out.println("str="+str.substring(1));

进入substring()

public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = length() - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        if (beginIndex == 0) {
            return this;
        }
        return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
                          : StringUTF16.newString(value, beginIndex, subLen);
}

分析:

  • 当 beginIndex < 0或者 beginIndex > length的时候,直接抛出越界异常;
  • 当 beginIndex 就是0 的时候,返回原字符串;
  • 最后判断是 isLatin1是否满足,进入StringLatin1/StringUTF16;

进入StringLatin1.newString

public static String newString(byte[] val, int index, int len) {
        return new String(Arrays.copyOfRange(val, index, index + len),
                          LATIN1);
}

分析:

  • byte[] val : 也就是str的构成数组,{A,B,C,D};
  • int index:beginIndex = 1;
  • int len :subLen = 4 -1 = 3;

再调用 Arrays.copyOfRange

public static byte[] copyOfRange(byte[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        byte[] copy = new byte[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

分析:

  • byte[] original:还是{A,B,C,D};
  • int from : index = 1;
  • int to :index + len = 1 + 3 = 4 (实际就是str的长度);
  • 该方法定义了一个新的数组,长度为:length - beginIndex = 3;

最后调用:
System.arraycopy

public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

分析:

  • 参数1,src ,源数组 ,传入 original,{A,B,C,D};
  • 参数2 ,srcPos 源数组的开始位置,传入 beginIndex = 1;
  • 参数3, dest ,目标数组,传入是一个空的 length 为 3的数组;
  • 参数4,destPos 目标数组的开始位置,传入 0;
  • 参数5,length 需要copy元素的数量,本次调用,传递的是 length - beginIndex = 3(经过最小值判断,仍然等价)
  • 结果:
    • copy[0] = original[1];
    • copy[1] = original[2];
    • copy[2] = original[3];

综上,str.subString(i) 实际上是

  1. 将 str 转成数组 array01,赋值给一个为新的数组 array02,并且array02.length = str.length - i;
  2. 赋值过程为:array02[0] = array01[i](直到i = array01.length)
  3. array02转换新的String,并返回;

得出结论:subString(i)返回值是 str的索引位置i,到最大索引(两个索引都包括)

原文地址:https://www.cnblogs.com/kangkaii/p/8419111.html