如何检查单词是否与文本文件中的大量单词匹配?

时间:2015-03-09 17:40:11

标签: c#

我已经使用过此代码,但搜索批量数据需要更多时间。我的文本文件包含超过一百万个单词,但所有单词都按字母顺序排列。如何以字典方式搜索单词。

int aCounter = 0; string aWordInTextFile;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Rider\Documents\Visual Studio 2012\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Resources\enable3.txt");
while((aWordInTextFile = file.ReadLine()) != null)
{
    Console.WriteLine (aWordInTextFile);
    if(textBox1.Text == aWordInTextFile){
        MessageBox.Show("String Match, found a string in notepad file");
        break;
    }
    aCounter++;
    Console.ReadLine();

}

file.Close();

1 个答案:

答案 0 :(得分:1)

由于单词已排序,您可以使用二进制搜索快速执行搜索部分:

string[] words = File.ReadAllLines(@"C:\Users\Rider\Documents\Visual Studio 2012\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Resources\enable3.txt");
int index = Array.BinarySearch(words, textBox1.Text);
if (index >= 0) {
  MessageBox.Show("String Match, found a string in notepad file");
}

但是,这种方法只有在您读取文件一次并在数据中进行多次搜索时才会更好。如果你只进行一次搜索,那么你所拥有的就像任何一个相当简单的解决方案一样好。

附注:您拥有的文件通常称为文本文件。记事本程序只是可以编辑文本文件的众多程序之一。

相关问题