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.

Kotlin Int to String

Having converted Kotlin Int to String, we will now explore the cases when we wish to convert an Int to a String. It usually happens when we wish to append an integer into a String.

The conversion from Kotlin Int to String can happen automatically when passes inside a print statement like below:

Read more

Kotlin String to Int

In modern languages, where the entire a lot of data is fetched to and from the applications. Every I/O is majorly worked in Strings. But the problems with String is their usability. I cant find the sum of two Strings until and unless you wish to view a concatenated value.

Read more

Kotlin String

String form a very important part in terms of input and output. All the input and output processing (including file I/O, Stream I/O) for kotlin as similar to Java is done in the form of Strings. Now let’s recall the Java’s main function.

public static void main(String [] args){	
	//Here, if you refer args or run time arguments are again taken in the form of Strings.
}

Read more