如何替换kotlin中所有出现的子字符串

如何用Kotlin中的其他东西替换一部分字符串?

例如,把“早上”改成“晚上”,把“早上”改成“晚上”

"Good Morning".replace("Morning", "Night") 

在Kotlin标准库API参考中搜索函数总是有用的。 在这种情况下,您可以在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()) } 
 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