Replace multiple chars with multiple chars in string
Asked Answered
M

2

5

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?

Mask answered 21/7, 2021 at 8:42 Comment(0)
S
5

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)
Sulfonmethane answered 21/7, 2021 at 9:0 Comment(1)
Note that for API versions below 24, map.getOrDefault has to be replaced with map[it] ?: itMask
M
3

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

Marvismarwin answered 21/7, 2021 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.