22

负数可以用作Java中string.substring的结束索引吗?

例子:

String str = "test";
str.substring(0, str.indexOf("q"));

编辑:javadocs 中没有直接说endindex不能为负数。在其他语言和库中存在允许负 endindex 但不允许负 beginindex 的 substring 实现,因此明确说明这一点似乎是相关的。它也没有以任何方式暗示。(编辑:好的,这暗示得很松散,但是我和显然其他亲自问过我这个问题的人仍然觉得很不清楚。这本来是一个简单的问答,我提供的并不是我实际上试图找到答案这个琐碎的问题)

4

2 回答 2

44

No. Negative indices are not allowed.

From String#substring(int beginIndex, int endIndex):

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

While the documentation does not directly state that endIndex cannot be negative1, this can be derived. Rewriting the relevant requirements yields these facts:

  1. "beginIndex cannot be negative" -> beginIndex >= 0
  2. "beginIndex must be smaller than or equal to endIndex" -> endIndex >= beginIndex

Thus it is a requirement that endIndex >= beginIndex >= 0 which means that endIndex cannot be negative.


Anyway, str.substring(0, -x) can be trivially rewritten as str.substring(0, str.length() - x), assuming we have the same idea of what the negative end index should mean. The original bound requirements still apply of course.


1 Curiously, String#subSequence does explicitly forbid a negative endIndex. Given such, it feels that the documentation could be cleaned up such that both methods share the same simplified precondition text. (As a bonus: there is also an important typo in the "Java 7" subSequence documentation.)

于 2013-10-28T23:46:34.420 回答
5

,对子字符串的 endindex 使用负数以及大于字符串长度的数字将导致 StringIndexOutOfBoundsException。

(你不会相信在网上找到一个直接的答案是多么困难)

于 2013-10-28T23:36:45.293 回答