How to group words by first letter in Rust

1 Answer

0 votes
use std::collections::HashMap;

/// Groups words by their first letter.
fn group_by_first_letter(words: &[&str]) -> HashMap<char, Vec<String>> {
    let mut groups: HashMap<char, Vec<String>> = HashMap::new();

    for word in words {
        // Extract the first character of the word
        let first = word.chars().next().unwrap();

        // entry(first) returns an Entry enum that lets us insert if missing
        groups.entry(first)
              .or_insert_with(Vec::new)
              .push(word.to_string());
    }

    groups
}

fn main() {
    // List of words to group
    let words = [
        "Python", "JavaScript", "C", "Java", "C#", "PHP",
        "C++", "Pascal", "SQL", "Rust",
    ];

    let grouped = group_by_first_letter(&words);

    // Print each group 
    for (letter, group) in &grouped {
        println!("{}: {:?}", letter, group);
    }

    // Print the entire HashMap
    println!("{:?}", grouped);
}



/*
run:

J: ["JavaScript", "Java"]
P: ["Python", "PHP", "Pascal"]
S: ["SQL"]
R: ["Rust"]
C: ["C", "C#", "C++"]
{'J': ["JavaScript", "Java"], 'P': ["Python", "PHP", "Pascal"], 'S': ["SQL"], 'R': ["Rust"], 'C': ["C", "C#", "C++"]}

*/

 



answered Jan 17 by avibootz
...