Remove duplicate adjacent whitespaces from a string in Kotlin
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.
|
1 2 3 4 5 6 7 |
fun main() { val s = "Example Text" val filtered = s.replace("\\s+".toRegex(), " ") println(filtered) // Example Text } |
To remove whitespaces from the beginning and end of the string, call the trim() function before calling the replace() function.
|
1 2 3 4 5 6 7 |
fun main() { val s = " Example Text " val filtered = s.trim().replace("\\s+".toRegex(), " ") println(filtered) // Example Text } |
Alternatively, use the regex \s{2,} which matches with exactly two or more whitespace characters.
|
1 2 3 4 5 6 7 |
fun main() { val s = " Example Text " val filtered = s.trim().replace("\\s{2,}".toRegex(), " ") println(filtered) // Example Text } |
If the replace() function is called multiple times, it is recommended to compile the regular expression and invoke the replaceAll() function on the matcher.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.regex.Pattern private val pattern = Pattern.compile("\\s{2,}") fun main() { val s = " Example Text " val filtered = pattern.matcher(s).replaceAll(" ") println(filtered) // Example Text } |
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).
|
1 2 3 4 5 6 7 |
fun main() { val s = " Some Text " val filtered = s.filterNot { it.isWhitespace() } println(filtered) // SomeText } |
That’s all about removing duplicate adjacent whitespaces 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 :)