Sarah Multitasker
Sarah Multitasker

Reputation: 563

Replace multiple chars with multiple chars in string

I am looking for a possibility to replace multiple different characters with corresponding different characters in Kotlin.

As an example I look for a similar function as this one in PHP:

str_replace(["ā", "ē", "ī", "ō", "ū"], ["a","e","i","o","u"], word)

In Kotlin right now I am just calling 5 times the same function (for every single vocal) like this:

var newWord = word.replace("ā", "a")
newWord = word.replace("ē", "e")
newWord = word.replace("ī", "i")
newWord = word.replace("ō", "o")
newWord = word.replace("ū", "u")

Which of course might not be the best option, if I have to do this with a list of words and not just one word. Is there a way to do that?

Upvotes: 5

Views: 1630

Answers (2)

Ben Shmuel
Ben Shmuel

Reputation: 1989

Just adding another way using zip with transform function

val l1 = listOf("ā", "ē", "ī", "ō", "ū")
val l2 = listOf("a", "e", "i", "o", "u")

l1.zip(l2) { a, b ->  word = word.replace(a, b) }

l1.zip(l2) will build List<Pair<String,String>> which is:

[(ā, a), (ē, e), (ī, i), (ō, o), (ū, u)]

And the transform function { a, b -> word = word.replace(a, b) } will give you access to each item at each list (l1 ->a , l2->b).

Upvotes: 3

sidgate
sidgate

Reputation: 15244

You can maintain the character mapping and replace required characters by iterating over each character in the word.

val map = mapOf('ā' to 'a', 'ē' to 'e' ......)
val newword = word.map { map.getOrDefault(it, it) }.joinToString("")

If you want to do it for multiple words, you can create an extension function for better readability

fun String.replaceChars(replacement: Map<Char, Char>) =
   map { replacement.getOrDefault(it, it) }.joinToString("")


val map = mapOf('ā' to 'a', 'ē' to 'e', .....)
val newword = word.replaceChars(map)

Upvotes: 5

Related Questions