Exercícios de Rust
Word Frequency Counter in Rust
Count how often each word appears with a HashMap and print the most common ones.
O que você vai aprender
- split_whitespace
- entry().or_insert(0)
- 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 hash map: the word is the key and the number of times it appears is the value.
entry(word).or_insert(0) returns the counter for the word, creating it at 0 the first time. The pairs are then sorted by count, highest first, and by word when the counts are equal, so the output is always the same.
Pontos-chave
- entry creates the counter the first time.
- Sort by count, then by word.
take(3)keeps the top three.
Exemplo executável de Rust
main.rs
use std::collections::HashMap;
fn main() {
let text = "the quick brown fox jumps over the lazy dog the end";
let mut counts: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
let mut entries: Vec<(&str, u32)> = counts.into_iter().collect();
entries.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
for (word, count) in entries.iter().take(3) {
println!("{word}: {count}");
}
}
the: 3
brown: 1
dog: 1Pratique
Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.
Terminou esta lição?
Marque como aprendida para acompanhar seu progresso.
Seu progresso está salvo neste navegador Entre para mantê-lo em todos os dispositivos.
Pratique com um desafio
Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.
- Contar Palavras Conte as palavras em uma frase. Fácil
- Frequência de Caracteres Conte quantas vezes cada caractere aparece. Fácil