In this article, you will learn to reverse a string in different ways. We will learn step by step, how to reverse a string in Kotlin.
1. Reverse a string in Kotlin using for loop
Source Code:
Description:
In the above program, we have used for loop to reverse a string. First, we have stored the string in str variable which we want to reverse.
In a next line, for loop will iterate until str.length - 1. With each iteration, it will find the value of a string using str[str.length - 1 -i]. Same will be printed using print() function.
1. Reverse a string in Kotlin using for loop
Source Code:
fun main(args: Array<String>)
{
val str = "Hello World"
var charOfString = ""
for (i in 0..str.length - 1)
{
charOfString += str[str.length - 1 -i].toString()
}
print("Reversed String: $charOfString")
}
Output:{
val str = "Hello World"
var charOfString = ""
for (i in 0..str.length - 1)
{
charOfString += str[str.length - 1 -i].toString()
}
print("Reversed String: $charOfString")
}
Description:
In the above program, we have used for loop to reverse a string. First, we have stored the string in str variable which we want to reverse.
In a next line, for loop will iterate until str.length - 1. With each iteration, it will find the value of a string using str[str.length - 1 -i]. Same will be printed using print() function.
2. Reverse a string in Kotlin using recursion
Source Code:
Output:
fun main(args: Array<String>) {
val sentence = "Hello World"
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]
}
Description:
In the above program, we have used recursion to reverse the sentence string. Here we have written new function reverse(sentence: String): String, which takes a string input and returns string output.
Next, we have called reverse function and passed a string which wanted to reverse. As you can see inside the reverse() function we have called the function reverse(sentence.substring(1)) itself. It will recursively call itself until a string is empty sentence.isEmpty().
0 Comments