Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Kotlin Program to Remove All Whitespaces from a String
In this program, you'll learn to remove all whitespaces in a given string using regular expressions in Kotlin.
Example: Program to Remove All Whitespaces
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")
}
When you run the program, the output will be:
Original sentence: T his is b ett er. After replacement: Thisisbetter.
In the above program, we use String's replace() method to remove and replace the whitespaces in the string sentence.
We've used regular expression \\s that finds all white space characters (tabs, spaces, new line character, etc.) in the string. Then, we replace it with "" (empty string literal).
Here's the equivalent Java code: Java program to remove all whitespaces
Did you find this article helpful?