您的位置:首页 > 编程语言 > Go语言

A Tour of Go Exercise: Maps

2014-10-27 23:21 519 查看
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 (
"code.google.com/p/go-tour/wc"
"strings"
)

func WordCount(s string) map[string]int {
m := make(map[string]int)
strs := strings.Fields(s)
for _,value := range strs {
v, ok := m[value]
if !ok {
m[value] = 1
}else{
m[value] = v + 1
}
}
return m
}

func main() {
wc.Test(WordCount)
}


package main

import (
"code.google.com/p/go-tour/wc"
"strings"
)

func WordCount(s string) map[string]int {
m := make(map[string]int)
strs := strings.Fields(s)
for i := 0; i < len(strs); i++ {
v, ok := m[strs[i]]
if !ok {
m[strs[i]] = 1
}else{
m[strs[i]] = v + 1
}
}
return m
}

func main() {
wc.Test(WordCount)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: