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.
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.
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.
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() }
val pattern = "\\s+".toRegex() for (s in strings) result.add(s.replace(pattern, " "))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With