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?

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Note that for API versions below 24, map.getOrDefault has to be replaced with map[it] ?: it
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).

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.