在此程序中,您将学习在Kotlin中使用递归循环来反转给定的句子。
fun main(args: Array<String>) { val sentence = "Go work" val reversed = reverse(sentence) println("倒过来的句子是: $reversed") } fun reverse(sentence: String): String { if (sentence.isEmpty()) return sentence return reverse(sentence.substring(1)) + sentence[0] }
运行该程序时,输出为:
倒过来的句子是:KROW OG
在上面的程序中,我们有一个递归函数reverse()。
Iteration | 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" |
Final | reverse("") | - | "" + "k" + "r" + "o" + "W" + " " + "o" + "G" = "kroW oG" |
这是等效的Java代码:颠倒句子的Java程序