首页
学习
活动
专区
工具
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
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3233379

复制
相关文章

相似问题

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