-3
String str = "Nobody ever went broke by buying IBM";

System.out.println("Length of this string: "+ str.length());
System.out.println("The character at position 36: "+ str.charAt(36)); // i get error here
System.out.println("The substring from 36: "+ str.substring(36));// why no error here

I get output as follows :

Length of this string: 36
The character at position 36: error
The substring from 36: 

My question is why it is not showing error when when substring(36) is called, instead i am getting answer as empty space. Logically there is no char at index 36?? But i get error when i call charAt(36) because there is no 36 index ??

4

1 回答 1

2

这就是这些功能应该如何工作的方式。(假设java)。

来自 oracle文档

substring方法抛出 IndexOutOfBoundsException- 如果 beginIndex 为负数或大于此 String 对象的长度。

36 是字符串的长度,它不大于字符串的长度,因此调用substring成功。

charAt失败,因为 36 个字符位于索引 0 到 35 之间。查看 charAt 的文档

于 2013-06-10T14:59:34.413 回答