java字符串索引超出绑定异常 [英] java string index out of bound exception

查看:166
本文介绍了java字符串索引超出绑定异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个简单的问题,但我想知道为什么我有这样的String变量:

It seems like a simple question but I'm wondering why if I had some String variable like this:

String name = "John";

然后我正在使用这样的子串方法:

And then I'm using the substring method like this :

System.out.print(name.substring(3,4));

它工作正常,但如果我将5改为4或更高,我会得到 IndexOutOfBoundsException异常。但正如我理解索引正确,也没有4索引,但outpul将n

it works fine but if i'd change 4 for 5 or higher I get IndexOutOfBoundsException. But as i understand indexes correct there is no 4 index as well but the outpul will be "n"

J O H N
0 1 2 3 

有人可以解释这样吗行为?提前致谢!

Could someone explain such behavior? Thanks in advance!

推荐答案

substring 的第二个参数是 exclusive 上限 - 因此允许它等于字符串的长度,以便包含最后一个字符。同样,允许起始点在字符串的末尾是有意义的,只要结束等于开始,就会产生一个空字符串。

The second parameter to substring is an exclusive upper bound - so it's allowed to be equal to the length of the string, in order to include the last character. Likewise it makes sense to allow the starting point to be "at" the end of the string, so long as the end is equal to the start, yielding an empty string.

基本上,对于处理范围的API,将索引视为在字符之间而不是在它们之间通常是有意义的。例如:

Basically, for APIs which deal with ranges, it often makes sense to think of the indexes as being "between" characters rather than "on" them. For example:

  J O H N
 ^ ^ ^ ^ ^
 0 1 2 3 4

两个索引必须在显示的范围内,并且 endIndex index必须与 beginIndex 相同或在右边 - 然后子字符串是两个相应边界之间的字符:

Both indexes have to be within the range shown, and the endIndex index must be either the same as beginIndex or to the right - then the substring is the characters between the two corresponding boundaries:

"JOHN".substring(1, 3) is "OH"

  J O H N
   ^ ^ ^
   1   3

这与记录,当然


IndexOutOfBoundsException - 如果 beginIndex 为负数,或 endIndex 大于此String对象的长度,或 beginIndex 大于 endIndex

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

这篇关于java字符串索引超出绑定异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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