Reverse a string in Kotlin
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.
|
1 2 3 4 5 6 7 |
fun main() { var str = "Hello" var reverse = str.reversed() println(reverse) // olleH } |
2. Using StringBuilder
You can also use the reverse() function of the StringBuilder class to efficiently reverse a string, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun reverse(str: String): String { return StringBuilder(str).reverse().toString() } fun main() { var str = "Hello" var reverse = reverse(str) println(reverse) // olleH } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun reverse(str: String): String { var reverse = "" for (i in str.length - 1 downTo 0) { reverse += str[i] } return reverse } fun main() { var str = "Hello" var reverse = reverse(str) println(reverse) // olleH } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun reverse(str: String): String { val chars = CharArray(str.length) str.indices.forEach { chars[str.length - it - 1] = str[it] } return String(chars) } fun main() { var str = "Hello" var reverse =reverse(str) println(reverse) // olleH } |
Here’s an alternative solution using swapping:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
fun reverse(str: String): String { val chars: CharArray = str.toCharArray() var l = 0 var h = str.length - 1 while (l < h) { val c = chars[l] chars[l] = chars[h] chars[h] = c l++; h--; } return String(chars) } fun main() { var str = "Hello" var reverse = reverse(str) println(reverse) // olleH } |
That’s all about reversing a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)