Kotlin replace multiple words in string

You could write an extension that overloads String::replace:

fun String.replace(vararg replacements: Pair<String, String>): String {
    var result = this
    replacements.forEach { (l, r) -> result = result.replace(l, r) }
    return result
}


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

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

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

Tags:

Kotlin