Skip to main content

How to reverse a string in Kotlin

How to reverse a string in Kotlin.

Here's a step-by-step tutorial on how to reverse a string in Kotlin:

Step 1: Define the input string

First, you need to define the string that you want to reverse. You can do this by assigning a value to a variable of type String.

val inputString = "Hello, World!"

Step 2: Use the reversed() function

Kotlin provides a handy function called reversed() that can be used to reverse a string. This function returns a new string with the characters in reverse order.

val reversedString = inputString.reversed()

Step 3: Print the reversed string

To see the reversed string, you can use the println() function to print it to the console.

println(reversedString)

Full Example: Putting it all together, here's a complete example of how to reverse a string in Kotlin:

fun main() {
val inputString = "Hello, World!"
val reversedString = inputString.reversed()
println(reversedString)
}

Output: When you run the above code, it will output the following:

!dlroW ,olleH

Alternative Approach: Manual Reversal If you want to reverse a string without using the reversed() function, you can do so by iterating over the characters in the string and appending them in reverse order to a new string.

Here's an example of how to manually reverse a string in Kotlin:

fun reverseString(input: String): String {
var reversedString = ""
for (i in input.length - 1 downTo 0) {
reversedString += input[i]
}
return reversedString
}

fun main() {
val inputString = "Hello, World!"
val reversedString = reverseString(inputString)
println(reversedString)
}

Output: When you run the above code, it will produce the same output as before:

!dlroW ,olleH

That's it! You've learned how to reverse a string in Kotlin using both the reversed() function and a manual approach.