저는 현재 텍스트 파일에서 관련 용어/단어를 검색하는 작은 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
텍스트 파일의 모든 라인을 통해 이동하고 검색 문자열의 용어를 포함하는 모든 문장을 작성하는 선형 검색을 사용합니다. 지금까지
내 코드 : 파일의 인덱스를 구축 한 다음 색인을 가진 반면, 모든 검색 작업이 O(n)
하는 선형 검색과 마찬가지로 인덱스를 검색 할 경우가 훨씬 더 빨리 될 것
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