Exercise: Maps
题目:
Implement WordCount
. It should return a map of the counts of each “word” in the string s
. The wc.Test
function runs a test suite against the provided function and prints success or failure.
You might find strings.Fields helpful.
练习程序:
package main
import (
"golang.org/x/tour/wc"
"strings"
)
var string_count_map map[string]int
func WordCount(s string) map[string]int {
string_count_map = make(map[string]int)
string_count := strings.Fields(s)
for _, j := range string_count{
ok := false
_, ok = string_count_map[j]
if ok{
string_count_map[j] += 1
}else{
string_count_map[j] = 1
}
}
return string_count_map
}
func main() {
wc.Test(WordCount)
}
运行结果:
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.") =
map[string]int{"A":1, "a":2, "canal":1, "man":1, "panama.":1, "plan":1}
笔记:该题目旨在通过Maps的创建和赋值,从而实现对String中单词的计数功能,通过利用string.Fields将一个字符串进行切分,得到单词slice, 讲该slice中的每个单词作为map的key值进行赋值,而map的value则根据单词出现的次数进行自增+1计数。