I would like to count the occurrences of each letter in a String. The goal is to build up a HashMap<char,i32>
where the keys are all the characters in the string and the values are counts of occurrences.
Assume I am looping over char
values from a String or an input file. For each char
, if it has not yet been encountered, I need to add it to the HashMap
as a new key with a value of 1, but if it has been previously seen, I need to increment the value.
Here is code that works. Bear with me, I am very new to Rust:
use std::collections::HashMap;
fn main() {
let mut letter_counts: HashMap<char,i32> = HashMap::new();
let input_string = "Hello, world!";
let char_vec: Vec<char> = input_string.to_lowercase().chars().collect();
for c in char_vec {
if let Some(x) = letter_counts.get_mut(&c) {
*x = *x + 1;
} else {
letter_counts.insert(c,1);
}
}
println!("{:?}",letter_counts);
}
What I'd like to know is, is there an idiomatic way to do this in Rust? By idiomatic, I mean is there a standard library type (like Python's defaultdict
), or a method on HashMap (like Java's HashMap.computeIfAbsent
) that would make this simpler, clearer, and/or less error-prone than hand-coding the algorithm as I have done?