使用替换地图替换字符串上的多个单词

时间:2017-04-13 19:48:28

标签: string scala

我有替换地图

val replacements = Map( "aaa" -> "d", "bbb" -> "x", "ccc" -> "mx")

我想用相应的值替换字符串中每个映射键的出现次数。

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"

我已经完成了

val sb = new StringBuilder(str)
for(repl <- replacements.keySet) yield {
  sb.replaceAllLiterally(repl, replacement.get(repl))
}

但我希望更像mapfold这样的功能,其中我应用于字符串的函数返回另一个字符串而不需要在循环内修改的可变变量。

2 个答案:

答案 0 :(得分:19)

一个选项:在foldLeft上使用Mapstr作为初始参数:

replacements.foldLeft(str)((a, b) => a.replaceAllLiterally(b._1, b._2))
// res8: String = This d is very x and I would love to mxc

答案 1 :(得分:0)

我真的不喜欢这个,但它应该有效:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.doubleView, new SampleFragment(), "someTag");<br>
ft.addToBackStack(null);<br>
ft.commit();