Kotlin program to remove all whitespaces from a string

Removing all whitespaces from a string :

Kotlin doesn’t provide any string method to remove all whitespaces from a string. The only way to do it by replacing all blank spaces with an empty string.

The easiest way to do this is by using regex. \s regex matches all whitespaces in a string. We will use the replace method of string to replace these whitespaces with an empty string.

Kotlin program :

The below kotlin program removes all whitespaces from the givenString:

fun main() {
    val givenString = " The quick        brown   fox jumps over the lazy dog "

    print(givenString.replace("\\s".toRegex(),""))
}

It will print the below output :

Thequickbrownfoxjumpsoverthelazydog

Similar tutorials :