字符串子字符串索引可以是字符串的长度 [英] String substring index could be the length of string
问题描述
这是Java字符串问题.我使用substring(beginindex)
来获取子字符串.
考虑到String s="hello"
,该字符串的长度为5.但是,当我使用s.substring(5)
或s.substring(5,5)
时,编译器没有给我错误.字符串的索引应从0开始长度为1.
为什么不适用于我的情况?我认为s.substring(5)
应该给我一个错误,但是没有.
This is a Java string problem. I use the substring(beginindex)
to obtain a substring.
Considering String s="hello"
, the length of this string is 5. However when I use s.substring(5)
or s.substring(5,5)
the compiler didn't give me an error. The index of the string should be from 0 to length-1.
Why it doesn't apply to my case? I think that s.substring(5)
should give me an error but it doesn't.
推荐答案
我认为当我使用s.substring(5)时,它应该给我错误 没有
I think when I use s.substring(5), it should give me error while it didn't
为什么会这样?
返回一个新字符串,该字符串是该字符串的子字符串.子串 以指定索引处的字符开头,并扩展到 该字符串的结尾.
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
由于beginIndex
不大于endIndex
(在您的情况下为5),因此完全有效.您只会得到一个空字符串.
Since the beginIndex
is not larger than the endIndex
(5 in your case), it's perfectly valid. You will just get an empty String.
如果您查看源代码:
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);
.
Thus s.substring(5);
is equivalent to s.substring(5, s.length());
which is s.substring(5,5);
in your case.
当您调用s.substring(5,5);
时,由于您正在调用count
值为0的构造函数(这是私有程序包),因此它会返回一个空字符串(count
表示字符串中的字符数) ):
When you're calling s.substring(5,5);
, it returns an empty String since you're calling the constructor(which is private package) with a count
value of 0 (count
represents the number of characters in the String):
644 String(int offset, int count, char value[]) {
645 this.value = value;
646 this.offset = offset;
647 this.count = count;
648 }
这篇关于字符串子字符串索引可以是字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!