Remove whitespace from a string in Kotlin
This article explores different ways to remove whitespace from a string in Kotlin.
There are several whitespace characters in Kotlin. The most common is space, \t, \n, and \r.
The pattern for matching whitespace characters is \s. To remove all whitespace from the input string, you should use the pattern \s and replace the matches with an empty string.
|
1 2 3 4 5 6 7 |
fun main() { var str = "Kotlin Is Awesome" str = str.replace("\\s".toRegex(), "") println(str) // KotlinIsAwesome } |
To handle two or more consecutive whitespace in the input string, you should use the pattern \s+ and replace the matches with a single space.
|
1 2 3 4 5 6 7 |
fun main() { var str = "Kotlin Is Awesome" str = str.replace("\\s+".toRegex(), " ") println(str) // Kotlin Is Awesome } |
That’s all about removing whitespace from a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)