1. Introduction

Having to reverse the order of words in a sentence is not uncommon while developing software, and we can use Kotlin to solve this problem efficiently.

In this tutorial, we’ll explore various methods to reverse the order of words in a sentence using Kotlin.

2. Programmatic Approach

For a better understanding, the string “this is a complete sentence”, when reversed, becomes “sentence complete a is this”. In all the approaches we’ll discuss, we’ll start with the split() method with a whitespace delimiter to convert the sentence into a list of words before proceeding to other steps.

First, we can write a custom method that accepts a String parameter to reverse the order of words in a sentence:

fun reverseWordsInSentenceCustomMethod(sentence: String): String {
    val words = sentence.split(" ")
    val reversedStringBuilder = StringBuilder()

    for (word in words) {
        reversedStringBuilder.insert(0, "$word ")
    }

    return reversedStringBuilder.toString().trim()
}

In this method, after splitting the sentence into a list of words, we then iterate the list of words. We use a StringBuilder to construct the reversed string, and in each iteration, we insert the current word followed by a whitespace character at the beginning of the StringBuilder. Finally, we call the trim() method on the result to remove all trailing and leading whitespace.

Let’s test this method for correctness:

@Test
fun `reverse sentence using programmatic approach`() {
    val sentence = "this is a complete sentence"
    assertEquals("sentence complete a is this", reverseWordsInSentenceCustomMethod(sentence))
}

3. Using the reversed() and joinToString() Methods

To simplify the method above, we can split the sentence into an array of words, reverse the array, and then join the words back into a sentence without a for() loop:

fun reverseSentenceUsingReverseAndJoinToStringMethods(sentence: String): String {
    val words = sentence.split(" ")
    return words.reversed().joinToString(" ")
}

Here, we first split the sentence into an array of words using the split() method. We then reverse the array using the reversed() function and join the words back into a sentence using the joinToString() method.

Now, let’s test our method for correctness:

@Test
fun `reverse sentence using split and joinToString methods`() {
    val sentence = "this is a complete sentence"
    assertEquals(
        "sentence complete a is this",
        reverseSentenceUsingSplitAndJointToStringMethod(sentence)
    )
}

4. Using the fold() Method

Alternatively, we can use the fold() method to traverse the words in a sentence while building a new sentence by prepending each word within an accumulator function:

fun reverseSentenceUsingFoldMethod(sentence: String): String {
    return sentence.split(" ")
        .fold("") { accumulator, word -> "$word $accumulator" }
        .trim()
 }

In this method, we also split the sentence out into an array of words using the split() method. Subsequently, we call the fold() method to iterate the array and prepend each word to a recursively constructed sentence accumulator. Finally, we use the trim() method to remove any trailing or leading whitespace.

Now, let’s write the test for this method:

@Test
fun `reverse sentence using a fold method`() {
    val sentence = "this is a complete sentence"
    assertEquals("sentence complete a is this", reverseSentenceUsingFoldMethod(sentence))
}

5. Using a Stack

Lastly, we can use a Stack to achieve our goal. A stack operates on the principle of last in, first out (LIFO):

fun reverseWordsInSentenceUsingStack(sentence: String): String {
    val stack = Stack<String>()
    val words = sentence.split(" ")
    for (word in words) {
        stack.push(word)
    }
    val reversedSentence = StringBuilder()
    while (!stack.empty()) {
        reversedSentence.append("${stack.pop()} ")
    }
    return reversedSentence.toString().trim()
}

As usual, we first split the sentence into words using the split() method. We then push each word onto a Stack and then pop the words off the stack to create the reverse of the sentence.

Let’s also test this method to ensure it works as expected:

@Test
fun `reverse sentence using a stack`() {
    val sentence = "this is a complete sentence"
    assertEquals("sentence complete a is this", reverseWordsInSentenceUsingStack(sentence))
}

6. Conclusion

In this article, we’ve explored different methods to reverse the order of words in a sentence in Kotlin. The first approach is a custom one involving a for() loop and StringBuilder. We’ve also discussed other methods that use the reversed() method, the fold() method, and the Stack data structure.

Each of these approaches is fine, and our choice of which to use should depend on our project needs.

As always, the code samples and relevant test cases for this article can be found over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.