伟大伟大

[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)
}

posted @ 2021-03-03 21:31  wooHsi  阅读(60)  评论(0)    收藏  举报