softAai Blogs

Explore in-depth insights on Kotlin, Android, Java, DSA, Design Patterns, Architectures, AI/ML, and Automotive/IVI. Discover best practices and knowledge all in one place: https://softaai.com/

Member-only story

Reversing Words in a String Using Kotlin: A Detailed Guide

3 min readMar 15, 2025

--

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]…

--

--

softAai Blogs
softAai Blogs

Published in softAai Blogs

Explore in-depth insights on Kotlin, Android, Java, DSA, Design Patterns, Architectures, AI/ML, and Automotive/IVI. Discover best practices and knowledge all in one place: https://softaai.com/

amol pawar
amol pawar

Written by amol pawar

Senior Android Developer | Software Engineer https://softaai.com/

No responses yet