Go-Übungen
Word Frequency Counter in Go
Count how often each word appears with a map and print the most common ones.
Das lernst du
- strings.Fields
- counts[word]++
- Sorting by count
counts
"the"3"brown"1"dog"1The word is the key, the count is the value
Counting words is a typical job for a map: the word is the key and the number of times it appears is the value.
counts[word]++ works even for a new word, because a missing key reads as 0. The words are then sorted by count, highest first, and alphabetically when the counts are equal, so the output is always the same.
Das Wichtigste
- A missing key reads as 0, so ++ just works.
- Sort by count, then by word.
words[:3]keeps the top three.
Ausführbares Go-Beispiel
main.go
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
text := "the quick brown fox jumps over the lazy dog the end"
counts := map[string]int{}
for _, word := range strings.Fields(text) {
counts[word]++
}
words := make([]string, 0, len(counts))
for word := range counts {
words = append(words, word)
}
sort.Slice(words, func(i, j int) bool {
if counts[words[i]] != counts[words[j]] {
return counts[words[i]] > counts[words[j]]
}
return words[i] < words[j]
})
for _, word := range words[:3] {
fmt.Printf("%s: %d\n", word, counts[word])
}
}
the: 3
brown: 1
dog: 1Üben
Öffne das Beispiel im Online-Compiler, ändere einen Wert oder füge eine Zeile hinzu und sage die Ausgabe voraus, bevor du es ausführst. Bring den Code danach absichtlich zum Scheitern und lies die Meldung des Compilers.
Lektion fertig?
Markiere sie als gelernt, um deinen Fortschritt zu verfolgen.
Dein Fortschritt ist in diesem Browser gespeichert Melde dich an, um ihn auf jedem Gerät zu behalten.
Mit einer Challenge üben
Nutze den Inhalt dieser Lektion, um ein echtes Problem zu lösen. Jede Challenge läuft im Browser, mit sofortigen Tests und einem KI-Review.
- Wörter zählen Zähle die Wörter in einem Satz. Einfach
- Zeichenhäufigkeit Zähle, wie oft jedes Zeichen vorkommt. Einfach