先做一个练习题:http://tour.golangtc.com/moretypes/18
练习:map
实现 `WordCount`。它应当返回一个含有 s
中每个 “词” 个数的 map。函数 wc.Test
针对这个函数执行一个测试用例,并打印成功或者失败。
你会发现 strings.Fields 很有帮助。
我的代码:
package main import ( "code.google.com/p/go-tour/wc" "strings" ) func WordCount(s string) map[string]int { str := strings.Fields(s)//把字符串分成单词数组 m := make(map[string]int) for i:=0;i<len(str);i++{ if m[str[i]]==0{ m[str[i]]=1 }else{ m[str[i]]++ } } return m } func main() { wc.Test(WordCount) }运行结果:
PASS
f("I am learning Go!") =
map[string]int{"I":1, "am":1, "learning":1, "Go!":1}
PASS
f("The quick brown fox jumped over the lazy dog.") =
map[string]int{"quick":1, "fox":1, "jumped":1, "the":1, "The":1, "over":1, "lazy":1, "dog.":1, "brown":1}
PASS
f("I ate a donut. Then I ate another donut.") =
map[string]int{"ate":2, "a":1, "donut.":2, "Then":1, "another":1, "I":2}
PASS
f("A man a plan a canal panama.") =
map[string]int{"A":1, "man":1, "a":2, "plan":1, "canal":1, "panama.":1}
有疑问加站长微信联系(非本文作者)