代码如下:
use std::collections::HashMap;
fn main() {
let text = "Hello world good world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{:#?}", map);
}
输出结果:
{
"Hello": 1,
"good": 1,
"world": 2,
}