Skip to content

Instantly share code, notes, and snippets.

@moogzy
Created November 3, 2016 12:39
Show Gist options
  • Save moogzy/7f2f71dea3d5eba261b85c899ee7c97e to your computer and use it in GitHub Desktop.
Save moogzy/7f2f71dea3d5eba261b85c899ee7c97e to your computer and use it in GitHub Desktop.
Exercise: Maps (Word count) - tour.golang.org/moretypes/23
package main
import (
"golang.org/x/tour/wc"
"strings"
)
// 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.
func WordCount(s string) map[string]int {
i := strings.Split(s, " ")
// i := strings.Fields(s) // This also works and splits a string on surrounding whitespace
m := make(map[string]int)
for j := 0; j < len(i); j++ {
m[i[j]]++
}
return m
}
func main() {
wc.Test(WordCount)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment