How to count the occurrences of each word in a string with Rust

1 Answer

0 votes
use std::collections::HashMap;

fn count_word_occurrences(s: &str) -> HashMap<String, usize> {
    let mut word_count = HashMap::new();
    
    for word in s.split_whitespace() {
        let counter = word_count.entry(word.to_string()).or_insert(0);
        *counter += 1;
    }
    
    word_count
}

fn main() {
    let s = "Rust is a general-purpose programming language emphasizing performance,  
             type safety, and concurrency. It enforces memory safety,  
             meaning that all references point to valid memory. It does so 
             without a conventional garbage collector";
            
    let word_count = count_word_occurrences(s);
    
    for (word, count) in &word_count {
        println!("{}: {}", word, count);
    }
}



/*
run:
     
safety,: 2
point: 1
general-purpose: 1
concurrency.: 1
does: 1
all: 1
to: 1
so: 1
emphasizing: 1
references: 1
It: 2
without: 1
Rust: 1
memory: 1
collector: 1
language: 1
that: 1
a: 2
and: 1
enforces: 1
performance,: 1
conventional: 1
programming: 1
type: 1
valid: 1
memory.: 1
garbage: 1
is: 1
meaning: 1
     
*/
 

 



answered Mar 1, 2025 by avibootz
...