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 get current IP form ipify.org ?
Example to handle GET and POST request in Golang
How to declare empty Map in Go?
Regular expression to validate the date format in "dd/mm/yyyy"
How to print struct variables data in Golang?
How to set, get, and list environment variables?
Golang import package inside package
What is Rune? How to get ASCII value of any character in Go?
Example: How to use ReadFull from IO Package in Golang?
How to create a photo gallery in Go?