Bài tập Rust

Word Frequency Counter in Rust

Count how often each word appears with a HashMap and print the most common ones.

  • Cơ bản
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • split_whitespace
  • entry().or_insert(0)
  • Sorting by count
counts
"the"3
"brown"1
"dog"1

The 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.

Những điểm quan trọng

  1. entry creates the counter the first time.
  2. Sort by count, then by word.
  3. take(3) keeps the top three.

Ví dụ Rust chạy được

Rust
Chạy code →
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}");
    }
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
the: 3
brown: 1
dog: 1

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Iterators →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách