我目前正在做一个小的C#练习,处理在文本文件中搜索相关的术语/单词,程序将写出包含搜索到的单词的文本文件中的所有句子。例如,我输入单词“example”,程序将执行的操作是遍历文本文件中的所有句子,并提取那些在其中包含单词“example”的句子。字符串线性搜索c#
The text file is structured as so: <sentenceDesignator> <text>
sentence 1: bla bla bla bla example of a sentence //each line contains a sentence
sentence 2: this is not a good example of grammar
sentence 3: bla is not a real word, use better terms
我想做些什么可以做的是使用线性搜索要经过所有的线路中的文本文件,并写入了包含搜索的字符串项的所有句子。
我迄今为止代码:
String filename = @"sentences.txt";
if (!File.Exists(filename))
{
// Since we just created the file, this shouldn't happen.
Console.WriteLine("{0} not found", filename);
return;
}
else
{
Console.WriteLine("Successfully found {0}.", filename);
}
//making a listof type "Sentence" to hold all the sentences
List<Sentence> sentences = new List<Sentence>();
//the next lines of code...
StreamReader reader = File.OpenText(filename);
//first, write out all of the sentences in the text file
//read a line(sentence) from a line in the text file
string line = reader.ReadLine();
while (line != null)
{
Sentence s = new Sentence();
//we need something to split data...
string[] lineArray = line.Split(':');
s.sentenceDesignator = lineArray[0];
s.Text = lineArray[1];
Console.Write("\n{0}", line);
line = reader.ReadLine();
}
//so far, we can write out all of the sentences in the text file.
Console.Write("\n\nOK!, search a term to diplay all their occurences: ");
string searchTerm = Console.ReadLine();
if(!line.Contains(searchterm))
{
Console.Write("\nThat term does not exist in any sentence.");
}
else
{
foreach (Sentence ss in sentences)
{
if (ss.sentenceDesignator.Contains(queryName))
{
//I need help here
}
}
}
那么什么似乎是问题吗? – AgentFire 2013-02-25 06:34:49