这个递归函数是如何中断和返回的



我是编码新手,对这个反向函数如何返回字符串感到困惑。我以为这将是一个无限循环。我知道当isEmpty()true时,它会断裂,但为什么sentence.isEmpty()会是true

public class Main {
public static void main(String[] args) {
String sentence = "Papa Jhon";
String reversed = reverse(sentence);
System.out.println("The reversed sentence is: " + reversed);
}
public static String reverse(String sentence) {
if (sentence.isEmpty())
return sentence;
return reverse(sentence.substring(1)) + sentence.charAt(0);
}
}

substring()返回作为该字符串的子字符串的字符串。子字符串以指定索引处的字符开始,并延伸到此字符串的末尾。

isEmpty()当且仅当length((为0时返回true。

String.substring(1)的调用将返回长度为String.length()-1String,最终将返回的String的长度减为零。这反过来又触发了String.isEmpty()

最新更新