How to remove the last word from a string in Kotlin

2 Answers

0 votes
fun removeLastWord(input: String): String {
    val lastSpaceIndex = input.lastIndexOf(' ')
    
    return if (lastSpaceIndex != -1) {
        input.substring(0, lastSpaceIndex)
    } else {
        input // return original if no space found
    }
}

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



/*
run:

c# kotlin c c++

*/

 



answered Sep 24, 2025 by avibootz
0 votes
fun String.removeLastWord(): String {
    val trimmed = this.trimEnd()
    val lastSpace = trimmed.lastIndexOf(' ')

    return if (lastSpace == -1) trimmed
    else trimmed.substring(0, lastSpace)
}

fun main() {
    var s: String

    s = "c c++ c# java python"
    println("1. ${s.removeLastWord()}")

    s = ""
    println("2. ${s.removeLastWord()}")

    s = "c"
    println("3. ${s.removeLastWord()}")

    s = "c# java python "
    println("4. ${s.removeLastWord()}")

    s = "  "
    println("5. ${s.removeLastWord()}")
}


/*
run:

1. c c++ c# java
2. 
3. c
4. c# java
5. 

*/

 



answered Mar 27 by avibootz
...