// Package words counts and finds words in a text. package words import ( "slices" "strings" ) // Sample is the text that both programs use. const Sample = "the quick cat sat on the mat and the dog sat on the cat" // Count counts how often each word appears, ignoring case. func Count(text string) map[string]int { counts := map[string]int{} for _, word := range strings.Fields(strings.ToLower(text)) { counts[word]++ } return counts } // Top returns the n most common words, most common first. Words with the same // count are sorted A to Z. func Top(counts map[string]int, n int) []string { words := []string{} for word := range counts { words = append(words, word) } slices.SortFunc(words, func(a, b string) int { if counts[a] != counts[b] { return counts[b] - counts[a] } return strings.Compare(a, b) }) if len(words) > n { words = words[:n] } return words } // Longest returns the longest word in text. When two are equally long, the // first one wins. A text with no words gives "". func Longest(text string) string { longest := "" for _, word := range strings.Fields(text) { if len(word) > len(longest) { longest = word } } return longest }