[A Tour of Go]Exercise: Maps
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"
)
func WordCount(s string) map[string]int {
m := make(map[string]int)
words := strings.Split(s, " ")
for _, word := range words {
elem, ok := m[word]
if ok {
m[word] = elem + 1
} else {
m[word] = 1
}
}
return m
}
func main() {
wc.Test(WordCount)
}

浙公网安备 33010602011771号