在Java语言中,我使用的是substring()
方法,我不确定它为什么没有抛出"out of index“错误。
字符串abcde
的索引从0到4,但是substring()
方法使用startIndex和endIndex作为参数,因为我可以调用foo.substring(0)并获取"abcde“。
那么为什么substring(5)可以工作呢?该索引应该超出范围。解释是什么?
/*
1234
abcde
*/
String foo = "abcde";
System.out.println(foo.substring(0));
System.out.println(foo.substring(1));
System.out.println(foo.substring(2));
System.out.println(foo.substring(3));
System.out.println(foo.substring(4));
System.out.println(foo.substring(5));
此代码输出:
abcde
bcde
cde
de
e
//foo.substring(5) output nothing here, isn't this out of range?
当我将5替换为6时:
foo.substring(6)
然后我得到了错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
发布于 2010-07-13 08:40:44
当您执行foo.substring(5)
时,它将获取从"e“之后的位置开始到字符串末尾结束的子字符串。顺便说一句,开始和结束位置恰好是相同的。因此,为空字符串。您可以认为索引不是字符串中的实际字符,而是字符之间的位置。
---------------------
String: | a | b | c | d | e |
---------------------
Index: 0 1 2 3 4 5
发布于 2010-07-13 08:42:01
这是因为substring函数返回一个“包含”子字符串。因此,索引5指向字符串末尾之前、字符串的最后一个显示字符之后的位置。
发布于 2010-07-13 08:50:23
从字符串API javadoc:
public String substring(int beginIndex)
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.
public String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this
string. The substring begins at the specified beginIndex
and extends to the character at index endIndex - 1. Thus
the length of the substring is endIndex-beginIndex.
示例:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
参数:
beginIndex - the beginning index, inclusive.
Returns:
the specified substring.
Throws:
IndexOutOfBoundsException - if beginIndex is negative or
larger than the length of this String object.
====
所以这是设计出来的。如果将索引作为字符串的大小,则返回空字符串。
https://stackoverflow.com/questions/3233379
复制相似问题