Reverse a String in Kotlin

In Kotlin, you can reverse a string by converting it to a StringBuilder object and using the reverse() method. Here’s an example code to reverse a string:

Kotlin
fun reverseString(str: String): String {
    val sb = StringBuilder(str)
    sb.reverse()
    return sb.toString()
}

In this code, the reverseString function takes a String parameter str and returns a new string with the characters of str reversed. The function creates a StringBuilder object sb initialized with the input string str, calls the reverse() method of sb to reverse its contents in place, and returns the reversed string using the toString() method of sb.

Here’s an example usage of the reverseString function:

Kotlin
fun reverseString(str: String): String {
    val sb = StringBuilder(str)
    sb.reverse()
    return sb.toString()
}
fun main() {
    val str = "hello world"
    val reversedStr = reverseString(str)
    println("Original string: $str")
    println("Reversed string: $reversedStr")
}

In this code, we create a string str with the value “hello world”. We then call the reverseString function to reverse the string, and print both the original and reversed strings to the console. The output will be:

Original string: hello world
Reversed string: dlrow olleh

Leave a Comment