How to move the n word to the end of a string in Kotlin

1 Answer

0 votes
fun moveNthWordToEndOfString(input: String, n: Int): String {
    val trimmed = input.trim()
    if (trimmed.isEmpty()) return trimmed

    val parts = trimmed.split(Regex("\\s+")).toMutableList()

    require(n in parts.indices) { "Index $n is out of range." }

    val word = parts.removeAt(n)
    parts.add(word)

    return parts.joinToString(" ")
}

fun main() {
    val s = "Would you like to know more? (Explore and learn)"
    val n = 2

    val result = moveNthWordToEndOfString(s, n)
    println(result)
}




/*
run:

Would you to know more? (Explore and learn) like

*/

 



answered Feb 6 by avibootz
...