为什么当我使用java子字符串(int beginIndex,int endIndex)时,即使我的参数超出范围,也没有抛出IndexOutOfBoundsException?

为什么当我使用java子字符串(int beginIndex,int endIndex)时,即使我的参数超出范围,也没有抛出IndexOutOfBoundsException?,java,Java,当我尝试substring()方法时,我发现java在代码中没有抛出IndexOutOfBoundsException,即使endIndex超出了范围 String str1 = "abcdefg"; System.out.println(str1.substring(3,7)); 当我将endIndex更改为8时,java在代码中抛出了IndexOutOfBoundsException String str1 = "abcdefg"; System.out.println(str1.subs

当我尝试substring()方法时,我发现java在代码中没有抛出IndexOutOfBoundsException,即使endIndex超出了范围

String str1 = "abcdefg";
System.out.println(str1.substring(3,7));
当我将endIndex更改为8时,java在代码中抛出了IndexOutOfBoundsException

String str1 = "abcdefg";
System.out.println(str1.substring(3,8));
我已经阅读了关于这种形式的子字符串的文档

我只记得在其他编程语言(如C)中,有一个称为空终止字符串的字符串,它添加在字符串的末尾 这是我的一些参考资料


所以,我只是想知道,java是否在字符串的末尾添加了一个以null结尾的字符串,这就是为什么这个代码片段“System.out.println(str1.substring(3,7));”没有抛出IndexOutOfBoundsException?

这是因为
子字符串(start,end)
函数指定包含的
开始
和独占的
结束
索引

通过这种方式,您可以指定一个比最大索引大1的
索引
,以指示您希望一直到字符串的末尾(尽管在这种情况下,您可能只需要使用自动抓取到字符串末尾的单个参数
子字符串(start)


如果以编程方式调用
子字符串(start,end)
函数w/computed
start
end
值,而不必检查字符串的大小并调用单参数版本,则此选项非常有用。

来自链接到的文档:

子字符串从指定的beginIndex开始,并延伸到索引endIndex-1处的字符


因此
str1。子串(3,7)
实际上是从索引3到索引6取一个子串。

其他两个解决方案中所述的是正确的。当您这样做时:

String str1 = "abcdefg";
System.out.println(str1.substring(3,7));
情况就是这样:

          v        v
[a][b][c][d][e][f][g]          --- return "defg"   
[0][1][2][3][4][5][6][7]       --- Grabbing index 3 to 6
          v           v
[a][b][c][d][e][f][g]          --- out of bounds, trying to read after last character   
[0][1][2][3][4][5][6][7]       --- Grabbing index 3 to 7
它正在从索引3读取到6,因为子字符串在指定的结束索引之前读取1个字符


但是,执行此操作时:

String str1 = "abcdefg";
System.out.println(str1.substring(3,8));
情况就是这样:

          v        v
[a][b][c][d][e][f][g]          --- return "defg"   
[0][1][2][3][4][5][6][7]       --- Grabbing index 3 to 6
          v           v
[a][b][c][d][e][f][g]          --- out of bounds, trying to read after last character   
[0][1][2][3][4][5][6][7]       --- Grabbing index 3 to 7

Java中没有以null结尾的字符,或者至少您不能将其视为Java字符串API的使用者。您看到的行为是通过阅读预期的。我认为当使用子字符串时,java将指向我放置的endIndex,然后向后移动1。所以,我的假设毕竟是错误的。现在我明白你在想什么了,是的,这是一个很好的猜测。