为何“超出范围”没有为'substring(startIndex,endIndex)'抛出 [英] Why is "out of range" not thrown for 'substring(startIndex, endIndex)'

查看:1333
本文介绍了为何“超出范围”没有为'substring(startIndex,endIndex)'抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Java I am using the substring() method and I'm not sure why it is not throwing an "out of index" error.

字符串 abcde 索引从0开始到4,但 substring()方法将startIndex和endIndex作为参数,基于我可以调用foo.substring(0)并获取abcde这一事实。

The string abcde has index start from 0 to 4, but the substring() method takes startIndex and endIndex as arguments based on the fact that I can call foo.substring(0) and get "abcde".

那么为什么子串(5)工作?该指数应该超出范围。解释是什么?

Then why does substring(5) work? That index should be out of range. What is the explanation?

/*
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?

当我用6替换5时:

foo.substring(6)

然后我收到错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
    String index out of range: -1


推荐答案

根据 Java API doc ,substring在启动索引时抛出错误大于字符串的 Length

According to the Java API doc, substring throws an error when the start index is greater than the Length of the String.


IndexOutOfBoundsException - 如果
beginIndex为负数或更大比
这个String对象的长度。

IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

事实上,他们举了一个像你的例子:

In fact, they give an example much like yours:

"emptiness".substring(9) returns "" (an empty string)

我想这意味着最好考虑一个Java String如下所示,其中索引包含在 | 中:

I guess this means it is best to think of a Java String as the following, where an index is wrapped in |:

|0| A |1| B |2| C |3| D |4| E |5|

这就是说字符串同时包含起始和结束索引。

Which is to say a string has both a start and end index.

这篇关于为何“超出范围”没有为'substring(startIndex,endIndex)'抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆