通过子字符串和 charAt 访问最后一个索引,但在 charAt() 中出错

Accessing last Index through substring and also with charAt but getting error in charAt()

例如,我现在有一个 String="something" 如果我要 访问最后一个索引(str.length()) 这个字符串的 给出“字符串索引超出范围:-1”。 但是如果我 通过 Substring 访问它,它不会给出任何错误。

String str="某事" str.charAt(9); 运行时间错误|| Str.substring(9);没有错误,它不会打印任何东西。

请帮忙

String#substring 文档清楚地提到(强调我的)

Throws:

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

索引将从 0 开始到 length-1 结束。

为了访问最后一个字符,您必须调用长度为 1 的 charAt 函数。

String str = "something";
str.charAt(str.length() - 1);

这将得到 g 作为结果。

请查看这两种方法的文档,您会有所了解。异常部分中提到了您的两个用例。 https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int) https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)