Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 373 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I replace duplicate whitespaces in a String in Kotlin?

#1
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.
Reply

#2
[`replace` function][2] 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()`][3] 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() }

<hr>
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, " "))


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through