我有一个字符串:
Template string:
I want to eat food, drink beverage at restaurant myrestaurant.
Hashmap:
food -> pizza
beverage -> miler light beer
myrestaurant -> Papa Johns
现在,我想编写一个for-yield loop
来替换模板字符串,其中包含hashmap中的所有键值。
解决它的最佳Scala方法是什么?
答案 0 :(得分:2)
您需要替换模板中的字词,因为您继续在hashmap
上进行迭代,
例如,
scala> val template = "I want to eat food, drink beverage at restaurant myrestaurant."
template: String = I want to eat food, drink beverage at restaurant myrestaurant.
scala> val hashmap = Map("food" -> "pizza", "beverage" -> "miler light beer", "myrestaurant" -> "Papa Johns")
hashmap: scala.collection.immutable.Map[String,String] = Map(food -> pizza, beverage -> miler light beer, myrestaurant -> Papa Johns)
scala> hashmap.foldLeft(template)((a: String, b: (String, String)) => a.replaceAll(b._1, b._2))
res40: String = I want to eat pizza, drink miler light beer at restaurant Papa Johns.
只有两个键(food
和beverage
)
scala> val hashmap = Map("food" -> "pizza", "beverage" -> "miler light beer")
hashmap: scala.collection.immutable.Map[String,String] = Map(food -> pizza, beverage -> miler light beer)
scala> hashmap.foldLeft(template)((a, b) => a.replaceAll(b._1, b._2))
res41: String = I want to eat pizza, drink miler light beer at restaurant myrestaurant.
答案 1 :(得分:0)
这样的事情:
(template /: hashMap) {case (t, (k, v)) => t.replace(k,v)}
(/:
是foldLeft的符号名称)
不确定为什么要为此获得收益率。