如何在Kotlin中使用.replace()将字符串的许多部分替换为其他部分

例如,我们只能通过替换一个单词来做到这一点

fun main(args: Array<String>) {

    var w_text = "welcome his name is John"

    println("${w_text.replace("his","here")}")
}

结果将是"欢迎光临,我叫约翰".

finally we need the result be " welcome here name is alles "

by replacing his to here and john to alles using .replace()

推荐答案

You can do it using multiple consecutive calls to replace():

w_text.replace("his", "here").replace("john", "alles")

Kotlin相关问答推荐

在Kotlin中可以连接两个范围吗?

CompositionLocal 究竟如何以及何时隐式设置值?

使用 StateFlow 时如何移除监听器?

Kotlin 可空泛型

在子类中覆盖 kotlin 运算符扩展函数

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

Picasso 回调

Saripaar formvalidation 在 kotlin 中第二次不起作用

SpringBoot 2.5.0 对于 Jackson Kotlin 类的支持,请在类路径中添加com.fasterxml.jackson.module: jackson-module-kotlin

找不到 androidsdk.modules

在用Kotlin编写的Android库公共API中处理R8+JvmStatic Annotation+Lambda

@uncheckedVariance 在 Kotlin 中?

有没有办法在数据类构建时转换属性的值?

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

如何解决:将Java类转换为Kotlin后出现error: cannot find symbol class ...?

添加抽象的私有getter和公共setter的正确方法是什么?

TornadoFX 中设置 PrimaryStage 或 Scene 属性的方法

以Kotlin为单位的货币数据类型

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

var str:String是可变的还是不可变的?