Meh*_*ğlu 6 hashmap case-insensitive rust
我正在尝试计算一个单词在文本中出现的次数。我正在使用HashMap并且我的实现忽略了大小写。我通过将所有单词转换为小写来实现这一点:
for line in reader.lines() {
for mut curr in line.as_ref().unwrap().split_whitespace() {
match word_map.entry(curr.to_string().to_lowercase()) {
Entry::Occupied(entry) => {
*entry.into_mut() += 1;
}
Entry::Vacant(entry) => {
entry.insert(1);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想考虑“the”和“The”相同,但如果“the”没有出现,只需在HashMap. 现在,我把所有的单词都写成小写。有什么有效的方法可以做到这一点吗?
最简单的方法是UniCase用作密钥:
use unicase::UniCase;
type Words = std::collections::HashMap<UniCase, u32>;
Run Code Online (Sandbox Code Playgroud)
如果我理解他们的文档,UniCase::new("The")将实际字符串存储"The"在其中,但是如果将其与 进行比较Unicase::new("the"),您会发现它是相同的字符串。