1. Introduction

In this tutorial, we’ll discuss the various methods we can use in Kotlin to iterate over a String backward. This means walking the characters of a String in reverse, starting from the last character and moving towards the first.

2. Using a for() Loop

Let’s take a look at how we can iterate a String backward in Kotlin using a for() loop:

class IterationTest {
    fun iterateStringWithForLoop(text: String): String {
        val reversedText = StringBuilder()
        for (i in text.length - 1 downTo 0) {
            val char = text[i]
            reversedText.append(char)
        }
        return reversedText.toString()
    }

    @Test
    fun testIterateStringWithForLoop() {
        val originalText = "Hello, Kotlin"
        val expectedReversedText = "niltoK ,olleH"
        val result = iterateStringWithForLoop(originalText)
        assertEquals(expectedReversedText, result)
    }
}

In this code, we’ve defined a function called iterateStringWithForLoop() that takes a String as input and returns the reversed version of our String. It starts from the last index and works towards the first index, using a StringBuilder to build the reversed string efficiently.
The output of this code will be “nitolK, olleH“.

3. Using Recursion

Recursion is a programming technique where a function calls itself in order to solve a problem. It involves breaking down a complex problem into simpler, similar subproblems and solving each subproblem until we reach a base case.

The base case is a condition that stops the recursion and provides a result without further recursive calls. In recursive functions, we have both the recursive case where the function calls itself, and the base case, which is the condition to exit the recursion.

Let’s use recursion to iterate a String backward:

class ReverseTest {
    fun reverse(sentence: String): String {
        if (sentence.isEmpty()) {
            return sentence
        }
        return reverse(sentence.substring(1)) + sentence[0]
    }

    @Test
    fun testReverseSentence() {
        val sentence = "Baeldung Team"
        val reversed = reverse(sentence)
        assertEquals("maeT gnudleaB", reversed)
    }
}

This code reverses our String using a recursive function. We start by defining our sentence and then call the reverse() function to reverse it. The reverse() function checks if the sentence is empty and, if not, moves the first character of the String to the end while recursively calling itself with the rest of the String.

It repeats this process until the String is empty, which is our base case. The reversed characters are then concatenated to form the reversed String.

4. Using the CharacterIterator

The CharacterIterator class provides a way to iterate over the characters of a String or a CharSequence. It traverses the characters one by one, forward or backward. It returns each character as it goes and allows for moving to the next or previous character.

The CharacterIterator interface provides methods like first(), last(), next(), and previous() to navigate through the characters in a String.

Let’s iterate over a String backward with a CharacterIterator:

class TraverseBackwardsTest {
    fun traverseBackwards(s: String): String {
        val it: CharacterIterator = StringCharacterIterator(s)
        var ch = it.last()
        val reversed = StringBuilder()
        while (ch != CharacterIterator.DONE) {
            reversed.append(ch)
            ch = it.previous()
        }
        return reversed.toString()
    }

    @Test
    fun testTraverseBackwards() {
        val s = "Kotlin Developer"
        val expectedOutput = "repoleveD niltoK"
        val result = traverseBackwards(s)
        assertEquals(expectedOutput, result)
    }
}

In this code, we first create a CharacterIterator initialized with the input String. We’ll start at the end of the input String by calling last(). Then, we’ll append each character in reverse order by calling previous() until we’ve reached CharacterItarator.DONE.

Finally, after we’ve visited all the characters in reverse order, we’ll convert our StringBuilder to a String with toString(). Now, we can return our reversed string as the result of the function.

5. Conclusion

In this article, we went through three methods we can use in Kotlin to iterate a String backward. Among these methods, we’ve looked at the use of recursion, a for() loop, and character iteration.

The full implementation of these examples is available over on GitHub.

Comments are closed on this article!