Created
September 14, 2013 01:10
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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