🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Kotlin 程序:使用递归来反转句子 > 原文: [https://www.programiz.com/kotlin-programming/examples/reverse-sentence](https://www.programiz.com/kotlin-programming/examples/reverse-sentence) #### 在此程序中,您将学习在 Kotlin 中使用递归循环来反转给定的句子。 ## 示例:使用递归反转句子 ```kt fun main(args: Array<String>) { val sentence = "Go work" val reversed = reverse(sentence) println("The reversed sentence is: $reversed") } fun reverse(sentence: String): String { if (sentence.isEmpty()) return sentence return reverse(sentence.substring(1)) + sentence[0] } ``` 运行该程序时,输出为: ```kt 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"` | 以下是等效的 Java 代码:[用来反转句子的 Java 程序](/java-programming/examples/reverse-sentence "Java Program to reverse a sentence")