GaMal
GaMal

Reputation: 183

Kotlin replace multiple words in string

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()

Upvotes: 17

Views: 18128

Answers (7)

remykarem
remykarem

Reputation: 2469

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

Upvotes: 2

Jossy Paul
Jossy Paul

Reputation: 1287

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

Upvotes: 0

Juan Rada
Juan Rada

Reputation: 3766

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

Upvotes: 11

avolkmann
avolkmann

Reputation: 3105

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"

}

Upvotes: 7

s1m0nw1
s1m0nw1

Reputation: 81939

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

Upvotes: 9

Mousa
Mousa

Reputation: 2290

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)

Upvotes: 6

Andrej Petrović
Andrej Petrović

Reputation: 907

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

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

Upvotes: 14

Related Questions