在哪里搜索?

时间:2013-02-27 06:54:25

标签: c# search syntax text-files

我目前正在做一个涉及文本文件的小型C#练习。所有文本文件都是文本文件中每个新行的句子。到目前为止,我能够将文本读取并存储到字符串数组中。我接下来需要做的是搜索特定的术语,然后写出包含搜索的单词/短语的任何句子。我只是想知道我是否应该在while循环或其他地方进行此操作?

String filename = @"sentences.txt";


// File.OpenText allows us to read the contents of a file by establishing
// a connection to a file stream associated with the file.
StreamReader reader = File.OpenText(filename);

if (reader == null)
{
   // If we got here, we were unable to open the file.
   Console.WriteLine("reader is null");
   return;
 }

  // We can now read data from the file using ReadLine.

 Console.WriteLine();

 String line = reader.ReadLine();


  while (line != null)
  {

     Console.Write("\n{0}", line);
     // We can use String.Split to separate a line of data into fields.


     String[] lineArray = line.Split(' ');
     String sentenceStarter = lineArray[0];

     line = reader.ReadLine();


  }
  Console.Write("\n\nEnter a term to search and display all sentences containing it: ");
        string searchTerm = Console.ReadLine();

        String searchingLine = reader.ReadLine();


        while (searchingLine != null)
        {


            String[] lineArray = line.Split(' ');
            String name = lineArray[0];



            line = reader.ReadLine();
            for (int i = 0; i < lineArray.Length; i++)
            {
                if (searchTerm == lineArray[0] || searchTerm == lineArray[i])
                {
                    Console.Write("\n{0}", searchingLine.Contains(searchTerm));
                }
            }
        }

2 个答案:

答案 0 :(得分:2)

您可以使用File类来简化操作。

要阅读文本文件中的所有行,您可以使用File.ReadAllLines

string[] lines = File.ReadAllLines("myTextFile.txt");

如果您想查找包含字词或遗赠的所有行,您可以使用Linq

// get array of lines that contain certain text.
string[] results = lines.Where(line => line.Contains("text I am looking for")).ToArray();

答案 1 :(得分:0)

问题:我只是想知道我是否应该在while循环或其他地方进行此操作?
答案:如果你不想(而且你不应该)将所有文件内容存储在内存中 - 在while循环中。否则你可以将while循环中的每一行复制到Listarray并在其他地方搜索它们(同样,对于大文件,这是非常资源贪婪的方法,不建议使用)

个人注意事项:
你的代码看起来很奇怪(特别是第二个while循环 - 它永远不会执行,因为文件已被读取,如果你想再次读取文件,你需要重置reader。除写入控制台外,第一个while循环没有任何用处......

如果这是真正的代码,你应该考虑修改它并用LINQ实现Matthew Watson的建议