go: characters frequency

Let’s explore characters frequency in the go string. Characters in go are in the format int32 – rune, and they can have any unicode value. Here is a simple go program https://play.golang.org/p/fbg7VXetxCg .

package main

import (
	"fmt"
	"sort"
)
func runeCharsFrequency(inpStr string) string {
	m := make(map[rune]int)
	for _, runeChar := range inpStr {
		m[runeChar]++
	}
	var keys []rune
	for kRune, _ := range m {
		keys = append(keys, kRune)
	}
	sort.Slice(keys, func(i, j int) bool {
		return keys[i] < keys[j]
	})

	outStr := ""
	comma := ""
	for _, k := range keys {
		outStr += fmt.Sprint(comma, k, ":", m[k])
		comma = ", "
	}
	return outStr
}
func main() {
        s := "Hello World!!!!!"
	fmt.Println("Characters frequency in string: "+s)
	fmt.Println(runeCharsFrequency(s))
}

Characters in the output have ordinal value and count:
32:1, 33:5, 72:1, 87:1, 100:1, 101:1, 108:3, 111:2, 114:1

This entry was posted in golang, workday. Bookmark the permalink.

Leave a Reply