kotlin: 字符串: replace()函数
一,功能:
String.replace方法的语法为:
String.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false): String
OldValue - 字符串中每次出现 oldValue 都必须替换为 newValue 的字符串。
ignoreCase - [可选] 如果为true,则在String中查找匹配项时将不考虑 oldValue 的字符大小写。
如果为false,则在字符串中查找 oldValue 的匹配项时将区分字符大小写。
ignoreCase的默认值为 false。
二,例子
代码:
binding.button2.setOnClickListener {
var str = "Kotlin Tutorial - Replace String - Programs"
val oldValue = "Programs"
val newValue = "Examples"
val output = str.replace(oldValue, newValue)
println("替换完成:"+output) //Kotlin Tutorial - Replace String - Examples
val oldValue2 = "PROGRAMS"
val newValue2 = "Examples"
val output2 = str.replace(oldValue, newValue, ignoreCase = true)
println("替换完成:"+output2) //Kotlin Tutorial - Replace String - Examples
}
运行结果:
三,例子:
代码:
//处理按钮点击事件
binding.button1.setOnClickListener {
var info = "hello world"
//替换为不同的字符
var str = info.replace(Regex("[ol]")){
when(it.value) {
"o" -> "欧"
"l" -> "了"
else -> it.value
}
}
println(str)
//替换为同一个字符
var str2 = info.replace(Regex("[ol]")){"中"}
println(str2)
}
运行结果: