Kotlin Program to Reverse a String

In this Kotlin tutorial, we will see three different ways to reverse a string.

Input String: I am Kotlin Programmer

Output String: remmargorP niltoK ma I

Let’s see each method one by one with program examples.

Method 1: Manually Traversing Each Character

In this method, we will manually traverse string characters from the end inside a loop and save them in a temporary variable.

fun main() {
    val s = "I am Kotlin Programmer"
    println("Input String: $s")
 
    var temp = ""
    var last = s.length - 1
 
    while (last >= 0) {
        temp += s[last]
        last--
    }
 
    println("Reversed String: $temp")
}

Output:

Input String: I am Kotlin Programmer
Reversed String: remmargorP niltoK ma I

Method 2: Using Recursion

In this method, we will recursively call a function that reverses the string.

fun main() {
    val s = "I am Kotlin Programmer"
    println("Input String: $s")
 
    var temp = reverseString(s)
 
    println("Reversed String: $temp")
}

fun reverseString(s: String): String {
    if (s.isEmpty())
        return s

    return reverseString(s.substring(1)) + s[0]
}

Method 3: Using reversed() Function

In this method, we will use an inbuilt function reversed(). Let’s see how this works.

fun main() {
    val s = "I am Kotlin Programmer"
    println("Input String: $s")
 
    var temp = s.reversed()
 
    println("Reversed String: $temp")
}

Now you have learned various ways to reverse a string in Kotlin. If you have any queries, feel free to ask in the comment section below.

Leave a Comment

Your email address will not be published. Required fields are marked *