String类中的子串方法到达它不应该的索引 [英] Substring method in String class reaches the index it isn't supposed to

查看:64
本文介绍了String类中的子串方法到达它不应该的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果标题不清楚,我道歉。

I apologize if title is not clear.

现在,字符串索引从0开始。例如:

Now, in strings index starts at 0. So for instance:

Index    0   1   2   3   4
String   H   E   L   L   O

在这种情况下,最后一个索引是4.

In this case, the last index is 4.

如果我尝试做这样的事情:

If I would try to do something like this:

System.out.println("hello".charAt(5));

它会抛出'Index Out of Bounds Exception',因为它应该。

It would throw an 'Index Out Of Bounds Exception', as it should.

但是,如果我尝试运行以下代码:

However, if I try to run the following code:

System.out.println("hello".substring(5));

确实有效!我写了类似的代码,稍后注意到这一点并且无法弄明白。

It does run! I wrote similar code, noticed this later and could not figure it out.

最后,问题是我们不应该达到这个指数的可能性如何?它允许我们写:

Eventually, the question is that how is this possible that we can reach this index we should not? It allows us to write:

stringObj.substring(stringObj.length());

并且它看起来不太安全,因为stringObj.length()返回一个整数,即1超过最后一个索引。

and it doesn't look very safe as stringObj.length() return us an integer that is one more than what the last index is.

是故意制作的,这是否有目的?如果是这样,这个目的是什么,它带来了什么好处?

Is it made intentionally and does this have a purpose? If so, what is this purpose and what is the benefit it brings?

推荐答案

使用<$ c $更容易c> substring 当你想到像这样的字符串中的索引时

It is easier to work with substring when you think of indexes in String like this

         H E L L O
        0 1 2 3 4 5
        ^         ^
        |         |
      start     length 
  (min index)  (max index)

当你子串从 a b ,您只能获得这些索引之间的字符。

When you substring from a to b you get only characters between these indexes.

因此,在HELLO.substring(2,4)的情况下,您将获得

So in case of "HELLO".substring(2,4) you will get

 L L 
2 3 4

返回LL

现在在 substring(5)的情况下,它与 substring(5,长度)这意味着在这种情况下它是 substring(5,5)。因此,由于 5 索引存在,我们的模型认为它是正确的,因为 5之间没有字符 5 我们得到空字符串作为结果。

Now in case of substring(5) it acts same as substring(5,length) which means in this case it is substring(5,5). So since 5 index exists in our model it is considered as correct, and since there are no characters between 5 and 5 we are getting empty string as result.

类似的情况发生在 substring(0,0) substring(1, 1)等等,只要我们的模型中存在索引。

Similar situation happens in case of substring(0,0) substring(1,1) and so on as long as indexes exist in our model.

StringIndexOutOfBoundsException 只有当我们尝试访问不在我们模型中的索引时才会发生:

StringIndexOutOfBoundsException happens only when we try to access indexes which are not in our model:


  • 否定的: -1 -2 ,...

  • 或大于长度 6 7 ,...

  • negative ones: -1, -2, ...
  • or greater than length 6 7, ...

这篇关于String类中的子串方法到达它不应该的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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