因为endIndex 是独占的,如documentation 中所指定。
IndexOutOfBoundsException - 如果 beginIndex 为负数,或者 endIndex
大于此 String 对象的长度,或 beginIndex 为
大于 endIndex。
我认为当我使用 s.substring(5) 时,它应该会给我错误
没有
为什么会这样?
返回一个新字符串,它是该字符串的子字符串。子串
从指定索引处的字符开始并延伸到
这个字符串的结尾。
由于beginIndex 不大于endIndex(在您的情况下为5),因此它完全有效。你只会得到一个空字符串。
如果你看source code:
1915 public String substring(int beginIndex) {
1916 return substring(beginIndex, count);
1917 }
....
1941 public String substring(int beginIndex, int endIndex) {
1942 if (beginIndex < 0) {
1943 throw new StringIndexOutOfBoundsException(beginIndex);
1944 }
1945 if (endIndex > count) {
1946 throw new StringIndexOutOfBoundsException(endIndex);
1947 }
1948 if (beginIndex > endIndex) {
1949 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1950 }
1951 return ((beginIndex == 0) && (endIndex == count)) ? this :
1952 new String(offset + beginIndex, endIndex - beginIndex, value);
1953 }
因此,s.substring(5); 等同于 s.substring(5, s.length());,在您的情况下为 s.substring(5,5);。
当你调用s.substring(5,5); 时,它返回一个空字符串,因为你调用构造函数(它是私有包),count 值为 0(count 表示字符串中的字符数):
644 String(int offset, int count, char value[]) {
645 this.value = value;
646 this.offset = offset;
647 this.count = count;
648 }