English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use regular expressions in Kotlin to remove all spaces from a given string.
fun main(args: Array<String>) { var sentence = "T his is b etter." println("Original string: $sentence") sentence = sentence.replace("\\s".toRegex(), "") println("Characters after removing spaces: $sentence") }
When running this program, the output is:
Original string: T his is b ett er. Characters after removing spaces: Thisisbetter.
In this program, we use the String's replaceAll() method to remove and replace all spaces in the string.
We used the regular expression \\s to find all whitespace characters (tabs, spaces, newlines, etc.) in the string. Then, we replaced them with "" (empty string literal).
This is the equivalent Java code:Java Program to Remove All Spaces