Skip to content
Advertisement

how to replace multiple chars efficiently with scala?

I want to replace 5 different chars to 5 different chars, and the current way im doing it looks stupid, so what would be a better way to do this?

currently:

 private def fixChars(str: String): String = {
    str.replaceAll("Ø","O")
    str.replaceAll("ø", "o")
    str.replaceAll("Ž","Z")
    str.replaceAll("ž","z")
    str.replaceAll("Ö","O")
}

?

Advertisement

Answer

I believe this approach will work for you and takes only one iteration to substitute all characters:

private def fixChars(str: String): String = {
  val substitutions = Map(
    'Ø' -> 'O',
    'ø' -> 'o',
    ...
  )
  str.map(c => substitutions.getOrElse(c, c))
}
Advertisement