How to reverse each word in a string with Kotlin

1 Answer

0 votes
fun reverseEachWordInString(s: String): String {
    // Split the string into words
    val words = s.split(" ")

    // Reverse each word
    val reversedWords = words.map { it.reversed() }

    // Join the reversed words back into a single string
    return reversedWords.joinToString(" ")
}

fun main() {
    val s = "java c++ rust python c# kotlin"
    
    val result = reverseEachWordInString(s)
    
    println(result)
}



/*
run:

avaj ++c tsur nohtyp #c niltok

*/

 



answered Sep 24, 2025 by avibootz
...