use*_*017 3 java string substring
这是一个Java字符串问题.我用它substring(beginindex)
来获取子串.考虑到String s="hello"
,这个字符串的长度是5.但是当我使用s.substring(5)
或s.substring(5,5)
编译器没有给我一个错误.字符串的索引应为0到length-1.为什么它不适用于我的情况?我认为这s.substring(5)
应该给我一个错误,但事实并非如此.
因为它endIndex
是独占的,如文档中所指定的那样.
IndexOutOfBoundsException - 如果beginIndex为负数,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex.
我想当我使用s.substring(5)时,它应该给我错误,而不是
为什么会这样?
返回一个新字符串,该字符串是此字符串的子字符串.子字符串以指定索引处的字符开头,并延伸到此字符串的末尾.
由于beginIndex
它不大于endIndex
(在你的情况下为5),它是完全有效的.你将得到一个空字符串.
如果你看一下源代码:
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 }
Run Code Online (Sandbox Code Playgroud)
因此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 }
Run Code Online (Sandbox Code Playgroud)
因为substring
是这样定义的,你可以在Javadoc 中找到它String.substring
@exception IndexOutOfBoundsException 如果 beginIndex 为负,或endIndex大于此 String 对象的长度,或 beginIndex 大于 endIndex。
这是在许多情况下非常有用,你总是可以创建一个子启动之后在一个字符串的字符。
因为endIndex
可以是字符串的长度,并且beginIndex
可以和字符串一样大endIndex
(但不能更大),所以beginIndex
等于字符串的长度也是可以的。