如何用Kotlin中的其他东西替换字符串的一部分?
例如,将“早上”改为“晚安”将“早上好”改为“晚安”
答案 0 :(得分:15)
fun main(args: Array<String>) {
var a = 1
// simple name in template:
val s1 = "a is $a"
a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
println(s2)
}
OUPUT: a为1,但现在为2
答案 1 :(得分:7)
"Good Morning".replace("Morning", "Night")
在Kotlin standard library API reference中搜索功能总是很有用。在这种情况下,您可以在Kotlin.text中找到替换函数:
/**
* Returns a new string with all occurrences of [oldChar] replaced with [newChar].
*/
public fun String.replace(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String {
if (!ignoreCase)
return (this as java.lang.String).replace(oldChar, newChar)
else
return splitToSequence(oldChar, ignoreCase ignoreCase).joinToString(separator = newChar.toString())
}