Write a Kotlin Program to Remove All Whitespaces from a String

In Kotlin, removing whitespaces from a string can be achieved in a straightforward way using the replaceAll() method with a regular expression that matches all whitespace characters.

Here’s a simple program that demonstrates how to remove all whitespaces from a string:

fun main() {
val strWithSpaces = "This is a string with spaces"
val strWithoutSpaces = strWithSpaces.replaceAll("\s", "")
println(strWithoutSpaces)
}

In the above code, we define a string strWithSpaces that contains some spaces.

We then call the replaceAll() method on the string, passing in a regular expression \s that matches any whitespace character (i.e., space, tab, newline, etc.).

The second argument to replaceAll() is an empty string, which effectively removes all matches found by the regular expression.

Finally, we print out the result, which should be the original string with all its whitespace removed.

That’s it! This program should work for any string containing whitespace characters, regardless of the number or type of whitespace characters involved.