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

如何在Kotlin中使用.replace()替换字符串中的多个内容

在Kotlin中替换字符串的多处内容

嘿,我来帮你搞定Kotlin里字符串多内容替换的问题~先从基础的单次替换入手,再一步步实现多处替换的需求。

单次替换示例

先看一个简单的单次替换场景:把字符串里的"his"替换成"here",代码如下:

fun main(args: Array<String>) { 
    var w_text = "welcome his name is John" 
    println("${w_text.replace("his","here")}") 
}

这段代码运行后,输出结果是:welcome here name is John

多处内容替换

如果要同时完成两个替换——把"his"换成"here"、"John"换成"alles",最直接的方式就是链式调用replace()方法,像这样:

fun main(args: Array<String>) { 
    var w_text = "welcome his name is John" 
    val finalResult = w_text.replace("his","here").replace("John","alles")
    println(finalResult) 
}

运行这段代码后,就能得到你想要的结果:welcome here name is alles

要是后续需要替换的内容更多,也可以用映射表配合循环的方式实现,但针对这种两处替换的场景,链式调用是最简洁易懂的方案~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:32:15