1

Is there a base function or simple way to replace multiple strings with multiple strings in a reference String?

I have seen Replace multiple strings with multiple other strings but it is using known lists instead of variable ones.

For example:

I have val str = "THE GOAT IS RED" , and I want to replace all the characters with other characters or digits, something like:

str.replace("THEGOAISRD".toList(), "0123456789".toList())  

To which will result

"012 3450 67 829"
htafoya
  • 18,261
  • 11
  • 80
  • 104

2 Answers2

4
val list1 = listOf('a', 'b', 'c')
val list2 = listOf('0', '1', '2')
val str = "abacada"
val transform = list1.withIndex().associate { it.value to list2[it.index] }
val result = str.map { transform[it] ?: it }.joinToString(separator = "")
println(result)

prints 01020d0

ardenit
  • 3,610
  • 8
  • 16
  • 2
    You could simplify it: `transform = list1.zip(list2).toMap()`. This even lets you skip the step of converting them to lists: `transform = "abc".zip("012").toMap()`. – Tenfour04 Jan 16 '20 at 19:01
0

You could do that by first building a dictionary (Map<Char, Char>) using zip and then iterating the string to transform with joinToString like that:

val str = "THE GOAT IS RED"

val dictionary = "THEGOAISRD".zip("0123475689").toMap()

val result = str.toCharArray().joinToString("") {
    dictionary.getOrDefault(it, it).toString()
}

println(result)
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121