Day 7:第六週總結練習
學習目標
- 綜合運用 Vec / HashMap / 迭代器 / 字串
- 寫一個完整的資料處理程式
今日重點
本週回顧
- Vec:建立、索引、迭代
- HashMap:insert / get / entry
- 迭代器:map / filter / fold / 惰性
- 自訂迭代器(Iterator trait)
- 字串:UTF-8、split / replace / 安全切片
綜合練習:文字分析工具
寫一支程式:統計一段文字的**單字頻率**,並排出前 3 名。
use std::collections::HashMap;
fn main() {
let text = "the quick brown fox jumps over the lazy dog the fox";
// 1. 用 split_whitespace + HashMap 計數
let mut freq: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
*freq.entry(word).or_insert(0) += 1;
}
println!("{:?}", freq);
// 2. 轉成 Vec<(word, count)> 並排序取前 3
let mut list: Vec<(&&str, &u32)> = freq.iter().collect();
list.sort_by(|a, b| b.1.cmp(a.1));
for (word, count) in list.iter().take(3) {
println!("{}: {}", word, count);
}
// 3. 用迭代器組合統計總字數與總單字數
let total_words = text.split_whitespace().count();
println!("總單字數: {}", total_words);
}
挑戰
- 把單字先
.to_lowercase()、去掉標點符號,再做頻率統計。 - 用
fold計算平均單字長度。
自我檢查
- 能綜合運用本週所有集合工具
- 會用 HashMap 做頻率統計
- 會用迭代器組合排序、取前 N
- 對 Rust 標準集合有信心
週總結
集合 + 迭代器讓你能高效地處理資料。下一週進入錯誤處理的體系化應用。