Created
September 26, 2018 23:42
-
-
Save ProProgrammer/6b16240a8da6a6b416c2e824c8c50c27 to your computer and use it in GitHub Desktop.
A Tour of Go: 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.
This file contains 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" | |
"golang.org/x/tour/wc" | |
"strings" | |
) | |
func WordCount(s string) map[string]int { | |
outputMap := make(map[string]int) | |
split_string := strings.Split(s, " ") | |
for _, item := range split_string { | |
_, ok := outputMap[item] // check if key exists in outputMap | |
if ok { | |
outputMap[item] += 1 | |
} else { | |
outputMap[item] = 1 | |
} | |
} | |
fmt.Println(outputMap) | |
return outputMap | |
} | |
func main() { | |
wc.Test(WordCount) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment