Hey. I solve this task - Exercise: Maps. I need to display the number of words in my map. How can I do this for my program?
Now I have instead of the number of words in the map, the length of each word is displayed:
map[I:1 need:4 help:4]
Hey. I solve this task - Exercise: Maps. I need to display the number of words in my map. How can I do this for my program?
Now I have instead of the number of words in the map, the length of each word is displayed:
map[I:1 need:4 help:4]
Hi @enzovitaliy, words stored already in your map. how about using len(map)? It will return number of words in your map.
Sorry, I did not say so. I need to display the number of one word in a string or map.
Can you post your expected output? since you have the map[I:1 need:4 help:4]
for example:
wc := WordCount("jingle bells jingle bells"):
output:
map[jingle:2 bells:2 jingle:2 bells:2]
or
map[jingle:2 bells:2]
Hi @enzovitaliy, Here’s my quick solution editing your existing code. maybe there is other solution like linked list etc… hope it helps to you.
package main
import (
"fmt"
"strings"
)
// WordCount funcion
func WordCount(s string) map[string]int {
str := strings.Fields(s)
m := make(map[string]int)
for _, j := range str {
if m[j] == 0 {
m[j] = 1
} else {
m[j] = m[j] + 1
}
}
return m
}
func main() {
wc := WordCount("jingle bells jingle bells bells")
fmt.Println(wc)
}
// Output:
map[jingle:2 bells:3]
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.