17

How to replace many parts of a string with something else in Kotlin using .replace()

For example, we can do it only by replacing one word

fun main(args: Array<String>) {

    var w_text = "welcome his name is John"

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

and the result will be " welcome here name is John " .

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

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

7 Answers 7

14

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

w_text.replace("his", "here").replace("john", "alles")
Sign up to request clarification or add additional context in comments.

1 Comment

What about s.replace("his", "JOHN").replace("JOHN", "Alles") ?
11

For the ones interested in replacing a map of values in a text:

private fun replaceText(text: String, keys: Map<String, String>): String =
    val replaced = map.entries.fold(text) { acc, (key, value) -> acc.replace(key, value) }

Comments

8

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")
}

Comments

7

Here is a one liner:

fun String.replace(vararg pairs: Pair<String, String>): String =
    pairs.fold(this) { acc, (old, new) -> acc.replace(old, new, ignoreCase = true) }

Test:

@Test fun rep() {

    val input = "welcome his name is John"

    val output = input.replace("his" to "her", "john" to "alles")

    println(output)

    output shouldBeEqualTo "welcome her name is alles"

}

Comments

6

If you have many of those replacement rules, then create a mapping of them and call the replace method in a loop:

val map = mapOf("his" to "here", "john" to "alles", ...)
val sentence = "welcome his name is John"
var result = sentence
map.forEach { t, u -> result = result.replace(t, u) }
println(result)

Comments

2

Similar to other responses but using Kotlin extension and overloading String::replace to accept a map of oldValue to newValue.

fun String.replace(mapping: Map<String, String>): String {
    var str = this
    mapping.forEach { str = str.replace(it.key, it.value) }
    return str
}

Usage:

val mapping = mapOf("his" to "here", "John" to "alles")
  
"his dad is John".replace(mapping)  // here dad is alles

Comments

0

The issue with just using replace without any regex is: Let's say I want to replace the occurrence of "here" with "there" inside the string "Where is my bag? Your bag is here." As you can imagine the result will be "Wthere is my bag? Your bag is there." which will not be correct. The solution is to use a regex like given below.

    var str = "Where is my bag? Your bag is here."
    val replacements = setOf("\\bhere\\b" to "there",
        "\\bjohn\\b" to "alles")
    replacements.forEach {
        str = str.replace(Regex(it.first), it.second)
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.