Introduction :
In this kotlin programming tutorial, we will learn how to reverse a string recursively in kotlin. The program will take the string from the user and reverse it. We will use one separate method and call it recursively to reverse the string.
Algorithm :
The algorithm we are using is like below :
- Ask the user to enter a string. Read and store it in a variable.
- Pass the string to a different function.
- Call this function recursively and add the first character to the end of the final string.
- Keep adding the current character to the end to build the final reverse string.
- Print out the string.
Kotlin program :
import java.util.Scanner
fun main(args: Array) {
//1
val scanner = Scanner(System.`in`)
//2
println("Enter the string : ")
var str = scanner.next()
//3
println(reverseStr(str))
}
//4
fun reverseStr(str: String): String{
//5
if(str.isEmpty())
return str
//6
return reverseStr(str.substring(1)) + str[0]
}
Explanation :
The commented numbers in the above program denote the step numbers below :
- Create one Scanner object to read the user input data.
- Ask the user to enter a string. Read the string and store it in str variable.
- Call one different function reverseStr and print out the result.
- reverseStr function takes one string as a parameter. It returns one String i.e. the reversed string.
- Inside the function, check if the current string is empty or not. If empty, return the same string.
- Else, call the reverseStr function again recursively. This time we are passing the substring starting from the second character. The final character we are adding to the end of the final string. This process will keep the start character adding to the end of the string on each step.
Sample Output :
Enter the string :
this
siht
Enter the string :
Hello
olleH
Enter the string :
world
dlrow
Enter the string :
universe
esrevinu
- [Trim leading whitespace characters using trimMargin in Kotlin
](https://www.codevscolor.com/kotlin-trim-leading-whitespace)