Rust使用HashMap统计出现次数

代码如下:

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,
}
posted @ 2022-04-10 11:48  诡局  阅读(171)  评论(0编辑  收藏  举报