如何在 Kotlin 中替换字符串中的重复空格?

2024-04-24

假设我有一个字符串:"Test me".

我如何将其转换为:"Test me"?

我尝试过使用:

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

但看来\\s是 Kotlin 中的非法转义。


replace功能 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/replace.htmlKotlin 中对原始字符串和正则表达式模式都有重载。

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

这替换了原始字符串\s+,这就是问题所在。

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

该行用一个空格替换多个空格。 注意明确的toRegex() https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-regex.html调用,这使得Regex from a String,从而指定过载Regex作为模式。

还有一个过载,可以让你从比赛中产生替代品。例如,要将它们替换为遇到的第一个空格,请使用以下命令:

"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, " "))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Kotlin 中替换字符串中的重复空格? 的相关文章

随机推荐