简体   繁体   中英

Go determine number of word occurences on a string slice

Having a hard time trying to figure out how can I count the number of apps or words on a slice using the go-lang code I made.

Hoping someone could help me figure out how to count the number of occurence?

https://play.golang.org/p/KvgI-lCz_c6

package main

import (
    "fmt"
)

func main() {

    apps := []string{"one", "two", "three", "one", "four"}
    fmt.Println("apps:", apps)

    o := CountOccurence(apps)

    fmt.Println("=== o: ", o)

}

func CountOccurence(apps []string) map[string]int {

    dict := make(map[string]int)
    for k, v := range apps {
        fmt.Println(k, v)

        dict[v] = k
    }

    // fmt.Println("=== dict: ", dict)

    return dict
}

Outputs the following

apps: [one two three one four]
0 one
1 two
2 three
3 one
4 four
=== o:  map[four:4 one:3 three:2 two:1]

PS: go strings.Count only counts a string, not a []string.

What you currently do is you gather the different elements and you assign their index to them. If a word occurs multiple times, the highest index will be assigned to it.

As you stated, you want to count the words. So instead of the index, assign 1 for new words (first occurrence), and if it's already in the map, increment its value by 1.

Since you can index a map with a non-existing key, in which case the result is the zero value of the value type of the map, which is 0 for int , it will tell you it was found 0 times (so far), so you don't even have to check if a key is already in there, just go ahead and increment it:

dict[v]++

So CountOccurrences() may look like this:

func CountOccurence(apps []string) map[string]int {
    dict := make(map[string]int)
    for _, v := range apps {
        fmt.Println(v)
        dict[v]++
    }
    return dict
}

Which will output (try it on the Go Playground ):

apps: [one two three one four]
one
two
three
one
four
=== o:  map[four:1 one:2 three:1 two:1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM