How to find common words in two strings with Rust

1 Answer

0 votes
use std::collections::HashSet;

/*
    Normalize a string:
    - Convert letters to lowercase
    - Replace any non-letter with a space
    This ensures consistent word comparison.
*/
fn normalize(text: &str) -> String {
    let mut result = String::with_capacity(text.len());

    for ch in text.chars() {
        if ch.is_ascii_alphabetic() {
            result.push(ch.to_ascii_lowercase());
        } else {
            result.push(' ');
        }
    }

    result
}

/*
    Extract words from a string.

    This function:
    - Normalizes the input
    - Splits on whitespace
    - Filters out empty entries
    - Returns a HashSet<String> for fast lookup and automatic duplicate removal
*/
fn extract_words(text: &str) -> HashSet<String> {
    let normalized = normalize(text);
    normalized
        .split_whitespace()
        .map(|w| w.to_string())
        .collect::<HashSet<String>>()
}

/*
    Find common words between two strings.

    This function:
    - Extracts words from both strings
    - Uses set intersection for efficiency
    - Returns a Vec<String> containing the common words
*/
fn find_common_words(a: &str, b: &str) -> Vec<String> {
    let words_a = extract_words(a);
    let words_b = extract_words(b);

    words_a
        .intersection(&words_b)
        .cloned()
        .collect::<Vec<String>>()
}

fn main() {
    let s1 = "The quick brown fox jumps over the lazy dog.";
    let s2 = "A lazy dog sleeps while the quick fox runs away.";

    let mut common = find_common_words(s1, s2);

    // Sort for stable output
    common.sort();

    println!("Common words:");
    for w in common {
        println!("{}", w);
    }
}


/*
run:

Common words:
dog
fox
lazy
quick
the

*/

 



answered Sep 11 by avibootz
...