【问题标题】:Accessing last Index through substring and also with charAt but getting error in charAt()通过子字符串和 charAt 访问最后一个索引,但在 charAt() 中出现错误
【发布时间】:2021-10-22 06:45:03
【问题描述】:

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

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

请帮忙

【问题讨论】:

  • 索引将从0开始。如果你想访问最后一个字符,你必须调用长度为-1的charAt => String str="something"; str.charAt(str.length() -1)
  • 好吧,阅读这两种方法的文档。那里提到了这种行为。

标签: java indexing substring


【解决方案1】:

请查看这两种方法的文档,您会有所了解。您的两个用例都在异常部分中提到。 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)

【讨论】:

    【解决方案2】:

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

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

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

    这将给出g 作为结果。

    【讨论】:

      【解决方案3】:

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

      投掷:

      IndexOutOfBoundsException - 如果 beginIndex 为负数或大于此 String 对象的长度

      【讨论】:

        猜你喜欢
        • 2014-05-01
        • 1970-01-01
        • 2018-05-09
        • 1970-01-01
        • 2013-11-09
        • 2015-10-01
        • 1970-01-01
        • 2013-08-10
        • 2013-04-05
        相关资源
        最近更新 更多