To remove all whitespace characters from a string in Kotlin, you can use the `replace` method with a regular expression.
In this example,
str
with a string value of "Hello World"
.replace
method with a regular expression \s+
to replace all whitespace characters (including tabs, spaces, newlines, etc.) with an empty string in str
.str
.fun main() {
val str = "Hello World"
val modifiedStr = str.replace(Regex("\\s+"), "")
println("Modified string: $modifiedStr")
}
Modified string: HelloWorld
In this example,
str
with a string value of "apple\tbanana\n cherry "
.replace
method with a regular expression \s+
to replace all whitespace characters (including tabs, spaces, newlines, etc.) with an empty string in str
.str
.fun main() {
val str = "apple\tbanana\n cherry "
val modifiedStr = str.replace(Regex("\\s+"), "")
println("Modified string: $modifiedStr")
}
Modified string: applebananacherry
In this tutorial, we learned How to Remove All Whitespace Characters from a String in Kotlin language with well detailed examples.