use std::collections::HashMap;
fn main() {
let s = "Hello World, Rust is great!".to_string();
let mut char_count: HashMap<char, u32> = HashMap::new();
// 处理Rust字符串中的字符
for c in s.chars() {
if c.is_alphabetic() {
*char_count.entry(c).or_insert(0) += 1;
}
}
let mut count_vec: Vec<(char, u32)> = char_count.into_iter().collect();
count_vec.sort_by_key(|&(_, count)| std::cmp::Reverse(count));
count_vec.sort_by_key(|&(c, _)| c);
for (c, count) in count_vec {
println!("{}: {}", c, count);
}
}
- 字符统计:
- 使用
HashMap<char, u32>
来统计每个字符出现的次数。
- 通过
for c in s.chars()
遍历Rust字符串中的每个字符。chars()
方法将Rust字符串拆分成一个个字符,这是处理Rust字符串字符的常用方式。并且通过c.is_alphabetic()
过滤掉非字母字符。
- 排序:
- 首先按照出现次数从高到低排序,使用
sort_by_key(|&(_, count)| std::cmp::Reverse(count))
。
- 然后对于出现次数相同的字符,按照字典序排序,使用
sort_by_key(|&(c, _)| c)
。
- 输出:
- 遍历排序后的
Vec<(char, u32)>
,输出每个字符及其出现次数。