使用替换映射替换字符串上的多个单词 [英] Replace multiple words on string using Map of replacements

查看:40
本文介绍了使用替换映射替换字符串上的多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张替换地图

val 替换 = 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"

我已经完成了

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

但我想要一些功能更强大的东西,比如 mapfold,其中我应用于字符串的函数返回另一个字符串,而无需在内部修改的可变变量循环.

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.

推荐答案

一个选项:在 Map 上使用 foldLeftstr 作为初始参数:

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

这篇关于使用替换映射替换字符串上的多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆