You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin实现仅替换字符串中最后出现的指定子串

Kotlin 替换字符串中最后一次出现的指定子串

要实现仅替换字符串中最后一次出现的指定子串,我们可以给String类添加一个扩展函数,借助Kotlin的字符串索引操作完成需求。

实现扩展函数

fun String.replaceLast(oldValue: String, newValue: String): String {
    if (oldValue.isEmpty()) return this
    val lastIndex = lastIndexOf(oldValue)
    return if (lastIndex == -1) {
        this // 子串不存在时直接返回原字符串
    } else {
        // 拆分原字符串,拼接替换后的内容
        substring(0, lastIndex) + newValue + substring(lastIndex + oldValue.length)
    }
}

使用示例

val originalStr = "ONE, TWO, THREE, FOUR"
val replacedStr = originalStr.replaceLast(",", " &")
println(replacedStr) // 输出: ONE, TWO, THREE & FOUR

逻辑说明

  1. 先校验目标子串oldValue是否为空,避免无效操作
  2. 通过lastIndexOf()获取子串最后一次出现的索引位置
  3. 若索引不存在(返回-1)则返回原字符串;否则拆分字符串并拼接替换后的结果

内容的提问来源于stack exchange,提问作者Leonardo Sibela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:17:04