This article explores different ways to reverse a string in Kotlin.

The string is immutable in Kotlin. This means we can’t reverse a string in-place by shuffling its characters. However, you can create a new string with characters of the original string in reversed order.

1. Using reversed() function

The standard way to reverse a string in Kotlin is with the reversed() function. It returns a string with characters in reversed order.

Download Code

2. Using StringBuilder

You can also use the reverse() function of the StringBuilder class to efficiently reverse a string, as shown below:

Download Code

3. Using + Operator

Here, the idea is to read characters from the end of the string and concat at the beginning of a new string using the + operator or plus() function. However, repeated string concatenation is costly. You can use the StringBuilder instance to reduce the total number of intermediate String objects.

Download Code

4. Using Character Array

Another efficient way to reverse a string in Kotlin is using the character array. The idea is to create an empty character array of the same size as that of the given string and fill the character array backward with corresponding characters from the original string. Then convert the character array into a new string using the String constructor.

Download Code

 
Here’s an alternative solution using swapping:

Download Code

That’s all about reversing a string in Kotlin.