[Go Tour] Exercise: Maps

Words: 97

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 sequence of test cases against it and reports pass or fail.

You will find strings.Fields helpful.

Reference code:

Go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"golang.org/x/tour/wc"
	"strings"
)

func WordCount(s string) map[string]int {
	stringList := strings.Fields(s)
	res := make(map[string]int)
	for _, word := range stringList {
		res[word]++
	}
	return res
}

func main() {
	wc.Test(WordCount)
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...