如何在Kotlin中替换字符串中的重复空格? [英] How do I replace duplicate whitespaces in a String in Kotlin?

查看:857
本文介绍了如何在Kotlin中替换字符串中的重复空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我尝试使用:

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

但看来\\s是科特林的非法逃生.

but it appears that \\s is an illegal escape in Kotlin.

推荐答案

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

这篇关于如何在Kotlin中替换字符串中的重复空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆