Member-only story
Reversing Words in a String Using Kotlin: A Detailed Guide
Reversing words in a sentence is a common programming task often used in coding interviews and algorithm-based challenges. In this blog, we’ll break down a Kotlin function that reverses the order of words in a given string. We’ll analyze each part of the code, identify potential improvements, and present an optimized version.
Problem Statement
Given an input string containing multiple words separated by spaces, we need to reverse the order of words while maintaining their original form.
Input:
"Hello India Pune World"
Output:
"World Pune India Hello"
Understanding the Kotlin Code
Let’s analyze the following Kotlin function that reverses the order of words in a string:
fun reverseInputStatement(input: String): String {
val wordList = input.split(" ")
val mutableWordList = wordList.toMutableList()
var indexFromEnd = mutableWordList.size - 1
for (indexFromStart in mutableWordList.indices) {
if (indexFromStart < indexFromEnd) {
val temp = mutableWordList[indexFromStart]
mutableWordList[indexFromStart] = mutableWordList[indexFromEnd]…