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
*/