Golang练习:map映射
实现单词统计, 它应当返回一个映射,其中包含字符串 s 中每个“单词”的个数。函数 wc.Test 会对此函数执行一系列测试用例,并输出成功还是失败。
package mainimport ("golang.org/x/tour/wc""strings")func WordCount(s string) map[string]int {var arrWord = strings.Fields(s) //初始化一个map[string]intmapWord := make(map[string]int)for i := 0; i < len(arrWord); i++ { //此处判断map是否存在指定key_, ok := mapWord[arrWord[i]]if ok {mapWord[arrWord[i]] += 1} else {mapWord[arrWord[i]] = 1}}return mapWord}func main() {wc.Test(WordCount)}
编译运行
go run main.go
PASS f("I am learning Go!") = map[string]int{"Go!":1, "I":1, "am":1, "learning":1}PASS f("The quick brown fox jumped over the lazy dog.") = map[string]int{"The":1, "brown":1, "dog.":1, "fox":1, "jumped":1, "lazy":1, "over":1, "quick":1, "the":1}PASS f("I ate a donut. Then I ate another donut.") = map[string]int{"I":2, "Then":1, "a":1, "another":1, "ate":2, "donut.":2}PASS f("A man a plan a canal panama.") =
练习完成