您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Kotlin 字符串替换

Kotlin 字符串替换

Kotlin中的字符串替换方法是 String.replace(oldValue,newValue)。 ignoreCase 是一个可选参数,可以作为replace()方法第三个参数。 在本教程中,我们将通过示例说明对于字符串中出现的每个 oldValue,我们将用一个新的值(另一个字符串)替换一个旧的值(String),以及忽略和不忽略 oldValue 的字符大小写用法。

语法

String.replace方法的语法为:

String.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false): String

OldValue - 字符串中每次出现 oldValue 都必须替换为 newValue 的字符串。

ignoreCase - [可选] 如果为true,则在String中查找匹配项时将不考虑 oldValue 的字符大小写。 如果为false,则在字符串中查找 oldValue 的匹配项时将区分字符大小写。 ignoreCase的默认值为 false。

Kotlin 替换子字符串,区分大小写

fun main(args: Array<String>) {
 
    var str = "Kotlin Tutorial - Replace String - Programs"
    val oldValue = "Programs"
    val newValue = "Examples"
 
    val output = str.replace(oldValue, newValue)
 
    print(output)
}

输出结果:

Kotlin Tutorial - Replace String - Examples

Kotlin 替换子字符串,不区分大小写

fun main(args: Array<String>) {
 
    var str = "Kotlin Tutorial - Replace String - Programs"
    val oldValue = "PROGRAMS"
    val newValue = "Examples"
 
    val output = str.replace(oldValue, newValue, ignoreCase = true)
 
    print(output)
}

输出结果:

Kotlin Tutorial - Replace String - Examples

在此Kotlin教程– Kotlin替换字符串中,我们学习了如何在字符串中用 新值 替换 旧值。 以及Kotlin示例替换字符串时忽略大小写的问题。


联系我
置顶