字符串处理
问题描述:
我想知道如果我在文本文件中有英文字典,检查给定字符串是否是正确和正确的英文单词的最佳方法是什么?我的字典包含大约10万个英语单词,我必须一次检查平均60000个单词。我只是在寻找最有效的方法。我也应该先存储所有的字符串,或者只是在生成时处理它们。字符串处理
感谢名单
答
100K是不是太大的数目,所以你可以放进一Hashset<string>
一切。
Hashset查找是基于密钥的,所以它会闪电般快速。
例如如何可能看起来在代码:
string[] lines = File.ReadAllLines(@"C:\MyDictionary.txt");
HashSet<string> myDictionary = new HashSet<string>();
foreach (string line in lines)
{
myDictionary.Add(line);
}
string word = "aadvark";
if (myDictionary.Contains(word))
{
Console.WriteLine("There is an aadvark");
}
else
{
Console.WriteLine("The aadvark is a lie");
}
答
如果你使用.NET 3.5或更高版本,您应该使用HashSet<string>
。
只需将有效单词字典加载到HashSet<string>
中,然后对每个候选字符串使用Contains
,或者使用某些集合运算符来查找所有无效的单词。
例如:
// There are loads of ways of loading words from a file, of course
var valid = new HashSet<string>(File.ReadAllLines("dictionary.txt"));
var candidates = new HashSet<string>(File.ReadAllLines("candidate.txt"));
var validCandidates = candidates.Intersect(valid);
var invalidCandidates = candidates.Except(valid);
您也不妨使用不区分大小写的比较或类似的东西 - 用StringComparer
静态属性来获取上,你可以通到HashSet
构造StringComparer
适当的实例。
如果你使用的是.NET 2,你可以使用Dictionary<string, whatever>
作为一个穷人的套装 - 基本上使用你喜欢的任何值作为值,然后检查密钥。
编辑回应说Hashset而不是字典,误解了问题。 – SWeko