How to count the occurrences of a word in a string using Rust

1 Answer

0 votes
fn count_occurrences(s: &str, word: &str) -> usize {
    s.split_whitespace()
     .filter(|&s| s == word)
     .count()
}

fn main() {
    let s = "Rust is a general-purpose programming language Rust enforces memory safety";
    let word = "Rust";
    
    let count = count_occurrences(s, word);
    
    println!("The word '{}' occurs {} times", word, count);
}



/*
run:
     
The word 'Rust' occurs 2 times
     
*/
 

 



answered Feb 28, 2025 by avibootz
edited Mar 1, 2025 by avibootz
...