How to count the occurrences of each word in a string with Go

1 Answer

0 votes
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 {
        _, exist := counts[word]
        if exist {
            counts[word] += 1
        } else {
            counts[word] = 1
        }
    }
    return counts
}
 
func main() {
    s := "go java c++ go c++ go php php python"   
    for word, count := range wordCount(s) {
        fmt.Println(word, "=", count)
    }
}

   
   
/*
run:
   
c++ = 2
php = 2
python = 1
go = 3
java = 1
 
*/

 



answered Aug 9, 2020 by avibootz
...