Kotlin Program to Remove All Whitespaces from a String

Kotlin Program to Remove All Whitespaces from a String. In the below program, we use String’s replaceAll() method to remove and replace all whitespaces in the string sentence.

Kotlin Program to Remove All Whitespaces from a String

Source Code

fun main(args: Array<String>) {
    var sentence = "T    his is b  ett     er."
    println("Original sentence: $sentence")

    sentence = sentence.replace("\\s".toRegex(), "")
    println("After replacement: $sentence")
}

Output