Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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.

like image 449
Dina Kleper Avatar asked May 06 '16 10:05

Dina Kleper


People also ask

How do I remove whitespace from a string in Kotlin?

Using trim() function Since the string is immutable in Kotlin, it returns a new string having leading and trailing whitespace removed. To just remove the leading whitespaces, use the trimStart() function. Similarly, use the trimEnd() function to remove the trailing whitespaces.

What does trim () do in Kotlin?

Show activity on this post. trim in kotlin remove space int leading and trailing, but when android studio convert java code to kotlin ,convert trim() in java to trim{it <= ' '} in kotlin when change this to trim,It made no difference.


1 Answers

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, " ")) 
like image 115
hotkey Avatar answered Oct 02 '22 05:10

hotkey