我有替换地图
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))
}
但我希望更像map
或fold
这样的功能,其中我应用于字符串的函数返回另一个字符串而不需要在循环内修改的可变变量。
答案 0 :(得分:19)
一个选项:在foldLeft
上使用Map
,str
作为初始参数:
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();