Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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
...