首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么'substring(startIndex,endIndex)‘没有抛出"out of range“

为什么'substring(startIndex,endIndex)‘没有抛出"out of range“
EN

Stack Overflow用户
提问于 2010-07-13 08:36:34
回答 5查看 71.4K关注 0票数 18

在Java语言中,我使用的是substring()方法,我不确定它为什么没有抛出"out of index“错误。

字符串abcde的索引从0到4,但是substring()方法使用startIndex和endIndex作为参数,因为我可以调用foo.substring(0)并获取"abcde“。

那么为什么substring(5)可以工作呢?该索引应该超出范围。解释是什么?

代码语言:javascript
复制
/*
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));

此代码输出:

代码语言:javascript
复制
abcde
bcde
cde
de
e
     //foo.substring(5) output nothing here, isn't this out of range?

当我将5替换为6时:

代码语言:javascript
复制
foo.substring(6)

然后我得到了错误:

代码语言:javascript
复制
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
    String index out of range: -1
EN

回答 5

Stack Overflow用户

发布于 2010-07-13 08:40:44

当您执行foo.substring(5)时,它将获取从"e“之后的位置开始到字符串末尾结束的子字符串。顺便说一句,开始和结束位置恰好是相同的。因此,为空字符串。您可以认为索引不是字符串中的实际字符,而是字符之间的位置。

代码语言:javascript
复制
        ---------------------
String: | a | b | c | d | e |
        ---------------------
Index:  0   1   2   3   4   5
票数 16
EN

Stack Overflow用户

发布于 2010-07-13 08:42:01

这是因为substring函数返回一个“包含”子字符串。因此,索引5指向字符串末尾之前、字符串的最后一个显示字符之后的位置。

这在文档中显示:http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#substring(int)

票数 3
EN

Stack Overflow用户

发布于 2010-07-13 08:50:23

从字符串API javadoc:

代码语言:javascript
复制
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.

示例:

代码语言:javascript
复制
"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"

参数:

代码语言:javascript
复制
beginIndex - the beginning index, inclusive.
Returns:
the specified substring.
Throws:
IndexOutOfBoundsException - if beginIndex is negative or 
larger than the length of this String object.

====

所以这是设计出来的。如果将索引作为字符串的大小,则返回空字符串。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3233379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档