A Tour of Go系列。如有问题欢迎指出~
Tour第二篇,直接贴代码吧,同样很简单。
1 package main
2
3 import (
4 "code.google.com/p/go-tour/wc"
5 "strings"
6 )
7
8 func WordCount(s string) map[string]int {
9 cntWord:=make(map[string]int)
10 for _,v:=range strings.Fields(s){
11 cntWord[v]+=1
12 }
13 return cntWord
14 }
15
16 func main() {
17 wc.Test(WordCount)
18 }
Run一下将输出:
PASS
f("I am learning Go!") =
map[string]int{"I":1, "learning":1, "Go!":1, "am":1}
PASS
f("The quick brown fox jumped over the lazy dog.") =
map[string]int{"over":1, "lazy":1, "quick":1, "brown":1, "the":1, "dog.":1, "fox":1, "jumped":1, "The":1}
PASS
f("I ate a donut. Then I ate another donut.") =
map[string]int{"donut.":2, "another":1, "ate":2, "Then":1, "I":2, "a":1}
PASS
f("A man a plan a canal panama.") =
map[string]int{"plan":1, "man":1, "A":1, "panama.":1, "a":2, "canal":1}
注意:
- 初始化map应用make这个built-in的函数,其返回生成map的引用。map中的值被自动初始化为0(值为int类型是时,其他类型类似)
- 第10行的for _,v:=...中的"_"类似于Lua中的哑元,函数返回时该位置的值将被略过。
- strings.Fields函数将一个string根据其中的空白字符将其分成一个[]string数组,类似于split
来源:https://www.cnblogs.com/so-what/archive/2012/10/10/2719086.html