Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,276 questions

52,302 answers

573 users

How to group words in a string by the first N letters in Rust

2 Answers

0 votes
use regex::Regex;
use std::collections::HashMap;

fn group_by_first_n_letters(s: &str, n: usize) -> HashMap<String, Vec<String>> {
    let re = Regex::new(r"[A-Za-z]+").unwrap();
    let mut groups: HashMap<String, Vec<String>> = HashMap::new();

    for word in re.find_iter(&s.to_lowercase()) {
        let w = word.as_str();
        if w.len() >= n {
            let prefix = &w[..n];
            groups.entry(prefix.to_string())
                  .or_default()
                  .push(w.to_string());
        }
    }

    groups
}

fn main() {
    let s = "The lowly inhabitants of the lowland were surprised to see \
             the lower branches of the trees.";

    let groups = group_by_first_n_letters(s, 3);

    // Print version 1
    for (prefix, words) in &groups {
        println!("{} : {:?}", prefix, words);
    }

    println!();

    // Print version 2
    for (prefix, words) in &groups {
        println!("{}: {}", prefix, words.join(", "));
    }
}




/*
run:

see : ["see"]
inh : ["inhabitants"]
tre : ["trees"]
sur : ["surprised"]
bra : ["branches"]
wer : ["were"]
low : ["lowly", "lowland", "lower"]
the : ["the", "the", "the", "the"]

see: see
inh: inhabitants
tre: trees
sur: surprised
bra: branches
wer: were
low: lowly, lowland, lower
the: the, the, the, the

*/

 



answered 1 day ago by avibootz
0 votes
use regex::Regex;
use std::collections::HashMap;

fn group_by_first_n_letters(s: &str, n: usize) -> HashMap<String, Vec<String>> {
    let re = Regex::new(r"[A-Za-z]+").unwrap();

    re.find_iter(&s.to_lowercase())
        .map(|m| m.as_str().to_string())
        .filter(|w| w.len() >= n)
        .fold(HashMap::new(), |mut groups, w| {
            let prefix = w[..n].to_string();
            groups.entry(prefix).or_default().push(w);
            groups
        })
}

fn main() {
    let s = "The lowly inhabitants of the lowland were surprised to see \
             the lower branches of the trees.";

    let groups = group_by_first_n_letters(s, 3);

    for (prefix, words) in &groups {
        println!("{}: {}", prefix, words.join(", "));
    }
}




/*
run:

tre: trees
bra: branches
low: lowly, lowland, lower
wer: were
sur: surprised
see: see
inh: inhabitants
the: the, the, the, the

*/

 



answered 1 day ago by avibootz
...