Golang : Individual and total number of words counter example
Problem:
You need to count the unique instances of words and the total number of words in a given string. For counting each unique occurrences of a word, you prefer to strip the word of any delimiter such as exclamation or question marks and return the result as a map.
Solution:
This code example below is self-explanatory. Happy coding!
package main
import (
"fmt"
"strings"
)
const delim = "?!.;,*"
func isDelim(c string) bool {
if strings.Contains(delim, c) {
return true
}
return false
}
func cleanDelimiter(input string) string {
size := len(input)
temp := ""
var prevChar string
for i := 0; i < size; i++ {
str := string(input[i]) // convert to string for easier operation
if (str == " " && prevChar != " ") || !isDelim(str) {
temp += str
prevChar = str
} else if prevChar != " " && isDelim(str) {
temp += ""
}
}
return temp
}
func SingleWordCount(s string, uniqueSensitive bool) map[string]int {
strSlice := strings.Fields(cleanDelimiter(s))
result := make(map[string]int)
if uniqueSensitive {
for _, str := range strSlice {
result[str]++
}
} else {
for _, str := range strSlice {
result[strings.ToLower(str)]++
}
}
return result
}
func TotalWordCount(s string) int {
strSlice := strings.Fields(cleanDelimiter(s))
return len(strSlice)
}
func main() {
str := "Hello fri3nd, you're looking good today!"
fmt.Println("======================================================")
fmt.Println(str)
fmt.Println("Count by individual word : ", SingleWordCount(str, true))
fmt.Println("Total words : ", TotalWordCount(str))
str = "Hello hello HELLo hellO"
fmt.Println("======================================================")
fmt.Println(str)
fmt.Println("Count by individual word : ", SingleWordCount(str, true))
fmt.Println("Total words : ", TotalWordCount(str))
// TREAT lower and upper case as the same
str = "Hello? hello!! HELLo?? hellO!"
fmt.Println("======================================================")
fmt.Println(str)
fmt.Println("Count by individual word : ", SingleWordCount(str, false)) // set to false
fmt.Println("Total words : ", TotalWordCount(str))
}
Output:
======================================================
Hello fri3nd, you're looking good today!
Count by individual word : map[today:1 Hello:1 fri3nd:1 you're:1 looking:1 good:1]
Total words : 6
======================================================
Hello hello HELLo hellO
Count by individual word : map[Hello:1 hello:1 HELLo:1 hellO:1]
Total words : 4
======================================================
Hello hello HELLo hellO
Count by individual word : map[hello:4]
Total words : 4
See also : Golang : Count number of runes in string
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+29.9k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+10.4k How to tell if a binary(executable) file or web application is built with Golang?
+3.9k Golang : Calculate a pip value and distance to target profit example
+27.9k Golang : JQuery AJAX post data to server and send data back to client example
+10k Use systeminfo to find out installed Windows Hotfix(s) or updates
+34.2k Golang : Validate IP address
+15k Golang : Test floating point numbers not-a-number and infinite example
+3.7k Golang : How to pass data between controllers with JSON Web Token
+11.3k Elastic Search : Return all records (higher than default 10)
+10.1k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+5.8k CloudFlare : Another way to get visitor's real IP address