如何使用 Kotlin 中的其他内容替换字符串的许多部分 .replace()
比如我们只需要替换一个词就可以做到
fun main(args: Array<String>) {
var w_text = "welcome his name is John"
println("${w_text.replace("his","here")}")
}
Run Code Online (Sandbox Code Playgroud)
结果将是“欢迎来到这里,名字是约翰”。
最后我们需要的结果是“欢迎这里的名字是 alles”
通过将他的to here和john替换为alles使用 .replace()
jcr*_*ada 10
对于那些有兴趣替换文本中的值映射的人:
private fun replaceText(text: String, keys: Map<String, String>): String =
val replaced = map.entries.fold(text) { acc, (key, value) -> acc.replace(key, value) }
Run Code Online (Sandbox Code Playgroud)
您可以使用多个连续调用来做到这一点replace():
w_text.replace("his", "here").replace("john", "alles")
Run Code Online (Sandbox Code Playgroud)
您可以编写一个重载扩展String::replace:
fun String.replace(vararg replacements: Pair<String, String>): String {
var result = this
replacements.forEach { (l, r) -> result = result.replace(l, r) }
return result
}
fun main(args: Array<String>) {
val sentence = "welcome his name is John"
sentence.replace("his" to "here", "John" to "alles")
}
Run Code Online (Sandbox Code Playgroud)
这是单行:
fun String.replace(vararg pairs: Pair<String, String>): String =
pairs.fold(this) { acc, (old, new) -> acc.replace(old, new, ignoreCase = true) }
Run Code Online (Sandbox Code Playgroud)
测试:
@Test fun rep() {
val input = "welcome his name is John"
val output = input.replace("his" to "her", "john" to "alles")
println(output)
output shouldBeEqualTo "welcome her name is alles"
}
Run Code Online (Sandbox Code Playgroud)
如果您有许多替换规则,则创建它们的映射并replace在循环中调用该方法:
val map = mapOf("his" to "here", "john" to "alles", ...)
val sentence = "welcome his name is John"
var result = sentence
map.forEach { t, u -> result = result.replace(t, u) }
println(result)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7402 次 |
| 最近记录: |