AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
# 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"` |