Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin replace multiple words in string

Tags:

kotlin

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

like image 367
GaMal Avatar asked May 22 '18 23:05

GaMal


People also ask

How do you replace words in a string in Kotlin?

The basic String Replace method in Kotlin is String. replace(oldValue, newValue). ignoreCase is an optional argument, that could be sent as third argument to the replace() method.

How do you replace all in Kotlin?

Android Dependency Injection using Dagger with Kotlin To replace all the consecutive whitespaces with a single space " ", use the replace() function with the regular expression "\s+" which matches with one or more whitespace characters.


2 Answers

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) }
like image 139
Juan Rada Avatar answered Oct 08 '22 07:10

Juan Rada


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"

}
like image 26
avolkmann Avatar answered Oct 08 '22 07:10

avolkmann