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