How to count number of repeating words in a given String?
In below program string Fields function used to splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.
Example
package main
import (
"fmt"
"strings"
)
func wordCount(str string) map[string]int {
wordList := strings.Fields(str)
counts := make(map[string]int)
for _, word := range wordList {
_, ok := counts[word]
if ok {
counts[word] += 1
} else {
counts[word] = 1
}
}
return counts
}
func main() {
strLine := "Australia Canada Germany Australia Japan Canada"
for index,element := range wordCount(strLine){
fmt.Println(index,"=>",element)
}
}
Most Helpful This Week
How to check lowercase characters in a string in Golang?
How to compare equality of struct, slice and map?
Get Year, Month, Day, Hour, Min and Second from a specified date
How to iterate over a Map using for loop in Go?
How to check if a string contains a white space in Golang?
How to get struct variable information using reflect package?
How to find out element position in slice?
Golang Get current Date and Time in EST, UTC and MST?
Golang Convert String into Snake Case
Regular expression to extract all Non-Alphanumeric Characters from a String