2013-02-27 86 views
0

我目前正在做一个涉及文本文件的小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)); 
       } 
      } 
     } 
+0

实施马修·沃森的建议,如果你有那么远,下一步不应该很难。 – 2013-02-27 06:58:22

+0

我知道,我只是想知道在哪里搜索。我想通过“lineArray”进行搜索,但在while循环之外,我无法在 – 2013-02-27 07:00:37

+0

之外执行断点,这发生在您复制粘贴代码时。 – 2013-02-27 07:03:52

回答

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(); 
+0

请注意,如果您使用Linq,则可以使用File.ReadLines()来避免将整个文件保存在内存中:string [] results = File.ReadLines(filename).Where(line => line.Contains (“我正在寻找的文本”))ToArray();' – 2013-02-27 07:37:03

+0

不,我用LINQ做了任何事情。我想知道的是现在在哪里搜索,我可以显示文本文件的所有内容。 – 2013-02-27 07:50:14

0

问题:我只想知道我是否应该在while循环或其他地方执行它?
答案:如果你不想(也不应该)将所有文件内容存储在内存中 - 在while循环中。否则,你可以在while循环中的每一行复制到Listarray和(再次,与大文件,这是非常资源贪婪的做法,不推荐使用)搜索里面别的地方

个人注释:
你的代码看起来很奇怪(尤其是第二个while循环 - 它将永远不会执行,因为文件已被读取,如果您想再次读取文件,则需要重置reader)。首先while循环无所作为有用的,除了写安慰......

如果这是真正的代码,你真的应该考虑修改它与LINQ

+0

谢谢。你的建议解决了我的问题。我已经修复了我的while循环... – 2013-02-28 16:42:42

+0

不客气。不要忘记上传和/或标记为回答对你的问题有用的评论(你有4个问题到目前为止与有价值的答案,但没有被接受)[如何问](http://stackoverflow.com/faq#howtoask)文章将为您提供更多信息 – Nogard 2013-02-28 17:34:44