Count Words in String with Golang
- Categories:
- golang
Below is example to count words in string with Golang. You can run this code snippet online via Golang Playground.
package main
import (
"fmt"
"strings"
)
func wordCount(s string) map[string]int {
// create map with string as key and integer as value
result := make(map[string]int)
// string.Fields splits the strings s and returns as a slice.
//
// Iterate with range so that we can assign result variable
// with substring as key and the word occurences as value.
//
// Default value of result[val] is 0, so we can just add one.
for _, val := range strings.Fields(s) {
result[val] += 1
}
return result
}
func main() {
fmt.Println(wordCount("hello world hello"))
fmt.Println(wordCount("world hello world aloha"))
}
Output
map[hello:2 world:1]
map[aloha:1 hello:1 world:2]