Skip to content

Instantly share code, notes, and snippets.

@mindscratch
Created September 14, 2013 01:10
Show Gist options
  • Select an option

  • Save mindscratch/6557920 to your computer and use it in GitHub Desktop.

Select an option

Save mindscratch/6557920 to your computer and use it in GitHub Desktop.
Using Go - count the number of times each word appears in a given string
package main
import (
"fmt"
"strings"
)
func WordCount(s string) map[string]int {
words := strings.Fields(s)
counts := make(map[string](int))
for _, word := range words {
count := counts[word]
count += 1
counts[word] = count
}
return counts
}
func main() {
result := WordCount("Hello there, how are you doing today? I hope you are doing well.")
fmt.Println(result) // output: map[Hello:1 how:1 you:2 well.:1 there,:1 are:2 doing:2 today?:1 I:1 hope:1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment