This article explores different ways to remove duplicate adjacent whitespaces from a string in Kotlin.

Since Strings are immutable in Kotlin, we can’t remove whitespaces from it. However, we can create a new string with duplicate whitespaces removed. To replace all consecutive whitespaces with a single space ' ', use the replace() function with regex \s+. The regular expression \s+ matches with one or more whitespace characters.

Download Code

 
To remove whitespaces from the beginning and end of the string, call the trim() function before calling the replace() function.

Download Code

 
Alternatively, use the regex \s{2,} which matches with exactly two or more whitespace characters.

Download Code

 
If the replace() function is called multiple times, it is recommended to compile the regular expression and invoke the replaceAll() function on the matcher.

Download Code

 
Finally, if we need to remove all whitespaces from the string, use the filterNot() function with the isWhitespace() function as the predicate (or filter() function with the reverse predicate).

Download Code

That’s all about removing duplicate adjacent whitespaces from a string in Kotlin.