Iterate over a string backward in Kotlin
This article explores different ways to iterate over a string backward in Kotlin.
1. Using for loop
You can use a simple for-loop to process each character of the string in the reverse direction. This approach is very effective for strings having fewer characters.
|
1 2 3 4 5 6 7 8 |
fun main() { val s = "Reverse String" // using simple for-loop for (i in s.length - 1 downTo 0) { print(s[i]) } } |
2. Convert to character array
In this approach, you initially reverse the string. Then you convert the reversed String to a character array by using the String.toCharArray() function. Finally, you iterate the char[] using a foreach loop, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val s = "Reverse String" // reverse the string and convert it to `char[]` array val chars = StringBuilder(s).reverse().toString() .toCharArray() // iterate over char[] using the foreach loop for (ch in chars) { print(ch) } } |
3. Using CharacterIterator
You can also use the CharacterIterator interface that provides bidirectional iteration for a String.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.text.CharacterIterator import java.text.StringCharacterIterator // Traverse the string backward, from end to start fun traverseBackwards(itr: CharacterIterator) { var ch = itr.last() while (ch != CharacterIterator.DONE) { print(ch) ch = itr.previous() } } fun main() { val s = "Reverse String" val it: CharacterIterator = StringCharacterIterator(s) traverseBackwards(it) } |
4. Using String.Split() function
String.split() splits the specified string and returns an array of strings created by splitting this string.
|
1 2 3 4 5 6 7 |
fun main() { val s = "Reverse String" val arr = s.split("".toRegex()).toTypedArray() for (i in arr.indices.reversed()) { print(arr[i]) } } |
That’s all about iterating over a string backward 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 :)