程序數組
public static void main(String[] args) {
String s = "字符串截取";
String substring = s.substring(0,2);
System.out.println(substring); // 字符
}
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); }
public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // 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); }
public static char[] copyOfRange(char[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); char[] copy = new char[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; }
本地方法網絡
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
說明:this
substring方法返回的字符串對象時新建立的,可是底層指向的字符數組並未改變,還指向原字符串對象指向的字符數組,僅僅是使用對象中的三個屬性來限制字符數組的開始位置與長度,展示給咱們的就是截取完的新字符串。spa
圖片來源網絡對象