英文:
Why doesn't this recursive function crash when it reaches s.substring(1) where s="y"?
问题
public static void recur(String s)
{
if(s.length() == 0)
return;
else
{
System.out.println(s.charAt(0));
recur(s.substring(1));
}
}
英文:
public static void recur(String s)
{
if(s.length() == 0)
return;
else
{
System.out.println(s.charAt(0));
recur(s.substring(1));
}
}
答案1
得分: 3
String that is substringed with its own length will return an empty string.
String s = "y";
System.out.println(s.substring(s.length()));
// prints out an empty string
So, when calling your recursive function with "y", it will run itself once again with an empty string, and the condition if (s.length() == 0) return;
will just exit from the function.
For details about String in Java, in the Java 6 Language Specification of 10.9:
In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).
Therefore, an empty String in Java is really empty. Getting the character at String.length()
will always result in string out of bound exception. That is,
String empty = "";
empty.charAt(0); // <= throws exception at runtime
英文:
String that is substringed with its own length will return an empty string.
String s = "y";
System.out.println(s.substring(s.length()));
// prints out an empty string
So, when calling your recursive function with "y"
, it will run itself once again with an empty string, and the condition if (s.length() == 0) return;
will just exit from the function.
For details about String in Java, in the Java 6 Language Specification of 10.9:
> In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).
Therefore, an empty String in Java is really empty. Getting the character at String.length()
will always result in string out of bound exception. That is,
String empty = "";
empty.charAt(0); // <= throws exception at runtime
答案2
得分: 2
String.substring(int)
的文档说明如下:
>抛出:
IndexOutOfBoundsException - 如果beginIndex为负数或大于此String对象的长度。
您的beginIndex始终为1(不是负数),对于空字符串,您不会到达此点,因为第一个if
语句已经返回。对于任何非空字符串,1
都不大于长度,因为在这种情况下,长度定义为>= 1。
英文:
The documentation of String.substring(int)
states
>Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
Your beginIndex is always 1 (not negative), for an empty string you do not reach this point since the first if
will already have returned. And for any non-empty string 1
is not larger than the length since the length in that case is by definition >= 1.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论