Replace multiple words with a string using Map of replacements
I have a substitution card
val replacements = Map( "aaa" -> "d", "bbb" -> "x", "ccc" -> "mx")
I would like to replace all occurrences of each map key in the string with the corresponding value.
val str = "This aaa is very bbb and I would love to cccc"
val result = cleanString(str, replacements)
result = "This d is very x and I would love to mx"
I did
val sb = new StringBuilder(str)
for(repl <- replacements.keySet) yield {
sb.replaceAllLiterally(repl, replacement.get(repl))
}
but I would like something more functional, for example, map
or fold
where the function I apply to the string returns another string without having to change the mutable variable inside the loop.
One option: use foldLeft
in Map
a str
as the initial parameter:
replacements.foldLeft(str)((a, b) => a.replaceAllLiterally(b._1, b._2))
// res8: String = This d is very x and I would love to mxc
I don't really like this, but it should work:
str.split(" ").toList.map { s =>
if(replacements.get(s).isDefined) {
replacements(s)
} else {
s
}
}.mkString(" ")