如何在 Kotlin 中替换字符串中的重复空格? [英] How do I replace duplicate whitespaces in a String in Kotlin?
问题描述
假设我有一个字符串:"Test me"
.
Say I have a string: "Test me"
.
如何将其转换为:Test me"
?
我试过使用:
string?.replace("\s+", " ")
但看起来 \s
在 Kotlin 中是非法转义.
but it appears that \s
is an illegal escape in Kotlin.
推荐答案
replace
函数 具有原始字符串和正则表达式模式的重载.
replace
function in Kotlin has overloads for either raw string and regex patterns.
"Test me".replace("\s+", " ")
这将替换原始字符串 s+
,这是问题所在.
This replaces raw string s+
, which is the problem.
"Test me".replace("\s+".toRegex(), " ")
这一行用一个空格替换了多个空格.注意显式的 toRegex()
调用,它从 String
生成一个 Regex
,从而使用 Regex
作为模式指定重载.
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
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, " "))
这篇关于如何在 Kotlin 中替换字符串中的重复空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!