แบบฝึกหัด Rust
Word Frequency Counter in Rust
Count how often each word appears with a HashMap and print the most common ones.
สิ่งที่คุณจะได้เรียนรู้
- 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.
ประเด็นสำคัญ
- entry creates the counter the first time.
- Sort by count, then by word.
take(3)keeps the top three.
ตัวอย่าง Rust ที่รันได้
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: 1ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- นับจำนวนคำ นับจำนวนคำในประโยคที่กำหนด ง่าย
- ความถี่ของตัวอักษร นับจำนวนครั้งที่ตัวอักษรแต่ละตัวปรากฏขึ้น ง่าย