2013-02-27 68 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

相關問題