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.

Download Code

 
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.

Download Code

That’s all about removing whitespace from a string in Kotlin.