/**
* 统计字符串中单词出现的次数
* @param str
*/
def countWords(str: String) = {
var map = Map.empty[String, Int]
for(word <- str.split("[,:!]")){
if(map.contains(word))
map += (word -> (map(word)+1))
else
map += (word -> 1)
}
map
}
def main(args: Array[String]) {
println(countWords("Jack,gates,jack,Lucy:jack,Gates!"))
}
输出结果: Map(jack -> 2, gates -> 1, Jack -> 1, Gates -> 1, Lucy -> 1)
另外可以思考 忽略大小写怎么统计 ?