我目前正在做一個涉及文本文件的小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));
}
}
}
實施馬修·沃森的建議,如果你有那麼遠,下一步不應該很難。 – 2013-02-27 06:58:22
我知道,我只是想知道在哪裏搜索。我想通過「lineArray」進行搜索,但在while循環之外,我無法在 – 2013-02-27 07:00:37
之外執行斷點,這發生在您複製粘貼代碼時。 – 2013-02-27 07:03:52