Home > Software design >  How to change every letter in a word using dictionary?
How to change every letter in a word using dictionary?

Time:10-17

So basically the title I want to change the word letters to another word but it says I have to specify the parameter

fun main() {
    val dictionary = mapOf( "c" to "b", "a" to "d" , "r" to "e"//here is the letters i want to change
        )
    val letters = "car"//the word i want to change
    
    for (me in letters){

        println(dictionary[me])


    }
}

i want for "car" to be "bde"

CodePudding user response:

Notice that your map has strings as keys, because you used string literals in these places:

val dictionary = mapOf( "c" to "b", "a" to "d" , "r" to "e")
                        ***         ***          ***

However, when you access the map, you are accessing it using me, which is a Char you got from the string letters. This causes the error.

I would suggest that you change the map to use Char keys instead. Change the string literals to character literals:

val dictionary = mapOf( 'c' to "b", 'a' to "d" , 'r' to "e")
                        ***         ***          ***

Notice that the letters are now surrounded with single quotes.

Though it is not required to solve this particular problem, you can also change the map's values to character literals too.

After that, you should use print instead of println to print the map values out, so that they are all printed on the same line:

for (me in letters){
    print(dictionary[me] ?: me.toString())
}

Note that I added the ?: me.toString() part so that if no replacement was found in the map, the original letter would be printed.

If you want a single string as the result, rather than having it printed out,

val result = letters.map { dictionary[it] ?: it.toString() }.joinToString("")
  • Related