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"
1
  • the result should actually be: 012 3470 56 829 doesn't it? Commented Jan 17, 2020 at 13:18

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.