How to reverse a word in a string with Kotlin

1 Answer

0 votes
fun reverseWord(str: String, word: String): String {
    val pos = str.indexOf(word)

    return if (pos != -1) {
        val reversed = word.reversed()
        str.substring(0, pos) + reversed + str.substring(pos + word.length)
    } else {
        str
    }
}

fun main() {
    val text = "C++ C Java Python PHP C# Kotlin"
    val target = "Java"

    val result = reverseWord(text, target)
    
    println(result)
}



/*
run:

c c# java php kotlin

*/

 



answered Sep 26, 2025 by avibootz
...