Search code examples
kotlinreplacereplaceall

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?


Solution

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