Reputation: 1203
I have a map of replacements
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 have done
val sb = new StringBuilder(str)
for(repl <- replacements.keySet) yield {
sb.replaceAllLiterally(repl, replacement.get(repl))
}
but I would like something more functional like a map
or fold
where the function I apply to the string returns another string without needing a mutable variable that is modified inside the loop.
Upvotes: 8
Views: 7390
Reputation: 63
You can use regex to do that. Be careful about the order.
val str = "aaaaaa"
val relaceMap = Map("aaaaa" -> "C", "a" -> "A", "aaa" -> "B")
val pattern = relaceMap.keys.mkString("|").r
val result = pattern.replaceAllIn(str, m => relaceMap(m.matched)) // CA
Upvotes: 0
Reputation: 3692
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(" ")
Upvotes: 0
Reputation: 214927
One option: use foldLeft
on the Map
with 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
Upvotes: 27