实现思路
- 使用
split_whitespace
方法按空白字符对字符串进行分词,这样可以避免不必要的内存分配和拷贝,因为它返回的是一个迭代器,每次迭代返回一个&str
类型的单词片段。
- 使用
HashMap
来统计每个单词出现的频率,HashMap
在查找和插入操作上具有较好的性能。
核心代码
use std::collections::HashMap;
fn main() {
let text = "this is a test string. this string is for testing word frequency.";
let mut word_count = HashMap::new();
for word in text.split_whitespace() {
// 去除单词两端的标点符号
let clean_word = word.trim_matches(|c| c.is_ascii_punctuation());
*word_count.entry(clean_word).or_insert(0) += 1;
}
for (word, count) in word_count {
println!("{}: {}", word, count);
}
}