package main
import (
"fmt"
"regexp"
"strings"
)
func groupByFirstNLetters(s string, n int) map[string][]string {
re := regexp.MustCompile(`[A-Za-z]+`)
words := re.FindAllString(strings.ToLower(s), -1)
groups := make(map[string][]string)
for _, w := range words {
if len(w) >= n {
prefix := w[:n]
groups[prefix] = append(groups[prefix], w)
}
}
return groups
}
func main() {
s := "The lowly inhabitants of the lowland were surprised to see the lower branches of the trees."
groups := groupByFirstNLetters(s, 3)
// Print version 1
for prefix, words := range groups {
fmt.Println(prefix, ":", words)
}
fmt.Println()
// Print version 2
for prefix, words := range groups {
fmt.Printf("%s: %s\n", prefix, strings.Join(words, ", "))
}
}
/*
run:
wer : [were]
sur : [surprised]
see : [see]
bra : [branches]
tre : [trees]
the : [the the the the]
low : [lowly lowland lower]
inh : [inhabitants]
wer: were
sur: surprised
see: see
bra: branches
tre: trees
the: the, the, the, the
low: lowly, lowland, lower
inh: inhabitants
*/