多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Java 程序:使用递归来反转句子 > 原文: [https://www.programiz.com/java-programming/examples/reverse-sentence](https://www.programiz.com/java-programming/examples/reverse-sentence) #### 在此程序中,您将学习使用 Java 中的递归循环来反转给定的句子。 ## 示例:使用递归反转句子 ```java public class Reverse { public static void main(String[] args) { String sentence = "Go work"; 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); } } ``` 运行该程序时,输出为: ```java The reversed sentence is: krow oG ``` 在上面的程序中,我们有一个递归函数`reverse()`。 在每次迭代中,我们使用`charAt(0)`将下一个`reverse()`函数的结果添加(连接)到句子的第一个字符。 递归调用必须在`charAt()`之前,因为这样最后一个字符将开始添加到左侧。 如果您颠倒顺序,您将得到原始句子。 最后,我们以空的`sentence`和`reverse()`返回相反的句子结束。 执行步骤 | 迭代 | `reverse()` | `substring()` | `reversedString` | | --- | --- | --- | --- | | 1 | `reverse("Go work")` | `"o Work"` | `result + "G"` | | 2 | `reverse("o Work")` | `" Work"` | `result + "o" + "G"` | | 3 | `reverse(" Work")` | `"Work"` | `result + " " + "o" + "G"` | | 4 | `reverse("Work")` | `"ork"` | `result + "W" + " " + "o" + "G"` | | 5 | `reverse("ork")` | `"rk"` | `result + "o" + "W" + " " + "o" + "G"` | | 6 | `reverse("rk")` | `"k"` | `result + "r" + "o" + "W" + " " + "o" + "G"` | | 7 | `reverse("k")` | `""` | `result + "k" + "r" + "o" + "W" + " " + "o" + "G"` | | 最后 | `reverse("")` | `-` | `"" + "k" + "r" + "o" + "W" + " " + "o" + "G" = "kroW oG"` |