【问题标题】:Why doesn't this recursive function crash when it reaches s.substring(1) where s="y"?为什么这个递归函数在到达 s.substring(1) where s="y" 时不会崩溃?
【发布时间】:2021-01-28 18:23:20
【问题描述】:
public static void recur(String s)
{
    if(s.length() == 0)
        return;
    else
    {
        System.out.println(s.charAt(0));
        recur(s.substring(1));
    }
}

【问题讨论】:

标签: java string


【解决方案1】:

以自己的长度作为子字符串的字符串将返回一个空字符串。

String s = "y";
System.out.println(s.substring(s.length()));
// prints out an empty string

因此,当使用"y" 调用您的递归函数时,它将再次以空字符串运行,而条件if (s.length() == 0) return; 将退出函数。


有关Java中String的详细信息,在the Java 6 Language Specification of 10.9

在 Java 编程语言中,与 C 不同,char 数组不是 String,String 或 char 数组都不会以 '\u0000'(NUL 字符)结尾。

因此,Java 中的空字符串实际上是空的。在String.length() 处获取字符将始终导致字符串超出范围异常。也就是说,

String empty = "";
empty.charAt(0); // <= throws exception at runtime

【讨论】:

  • 那么为什么 s.charAt(0) 不起作用? java字符串是否也像C一样有\0或\u0000或NUL字符?
  • 添加关于Java String的详细阐述
  • 它在 java 6 和今天之间没有变化,但 here 是当前的参考规范。
【解决方案2】:

String.substring(int) 状态的文档

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

您的 beginIndex 始终为 1(不是负数),因为第一个 if 已经返回,所以对于空字符串,您不会到达这一点。对于任何非空字符串,1 不大于长度,因为在这种情况下,长度定义为 >= 1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2010-10-26
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多