How do I replace duplicate whitespaces in a String in Kotlin?

Kotlin

Kotlin Problem Overview


Say I have a string: "Test me".

how do I convert it to: "Test me"?

I've tried using:

string?.replace("\\s+", " ")

but it appears that \\s is an illegal escape in Kotlin.

Kotlin Solutions


Solution 1 - Kotlin

replace function in Kotlin has overloads for either raw string and regex patterns.

"Test  me".replace("\\s+", " ")

This replaces raw string \s+, which is the problem.

"Test  me".replace("\\s+".toRegex(), " ")

This line replaces multiple whitespaces with a single space. Note the explicit toRegex() call, which makes a Regex from a String, thus specifying the overload with Regex as pattern.

There's also an overload which allows you to produce the replacement from the matches. For example, to replace them with the first whitespace encountered, use this:

"Test\n\n  me".replace("\\s+".toRegex()) { it.value[0].toString() }


By the way, if the operation is repeated, consider moving the pattern construction out of the repeated code for better efficiency:

val pattern = "\\s+".toRegex()

for (s in strings)
    result.add(s.replace(pattern, " "))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDina KleperView Question on Stackoverflow
Solution 1 - KotlinhotkeyView Answer on Stackoverflow