C# 在C语言中搜索文本文件中的单词#
我有一个包含三行文本的小txt文件。我正在尝试用C#创建一个程序,从用户那里获取一个单词,并在txt文件中搜索该单词。如果找到这个单词,我想记录并显示在txt文件中找到这个单词的行。变量int-position记录是否找到单词,但我不知道如何记录在哪些行上找到单词。我该怎么做?这是我的密码:C# 在C语言中搜索文本文件中的单词#,c#,C#,我有一个包含三行文本的小txt文件。我正在尝试用C#创建一个程序,从用户那里获取一个单词,并在txt文件中搜索该单词。如果找到这个单词,我想记录并显示在txt文件中找到这个单词的行。变量int-position记录是否找到单词,但我不知道如何记录在哪些行上找到单词。我该怎么做?这是我的密码: class Program { static void Main(string[] args) { Console.Write("please enter a file to sea
class Program {
static void Main(string[] args) {
Console.Write("please enter a file to search for");
string fileResponse = Console.ReadLine();
Console.Write("please enter a word to search for in the file");
string wordResponse = Console.ReadLine();
StreamReader myfile = File.OpenText(fileResponse);
string line = myfile.ReadLine();
int position = line.IndexOf(wordResponse);
int count = 0; //counts the number of times wordResponse is found.
int lineNunmber = 0;
while (line != null) {
if (position != -1) {
count++;
}
line = myfile.ReadLine();
}
if (count == 0) {
Console.WriteLine("your word was not found!");
} else {
Console.WriteLine("Your word was found " + count + " times!" + position);
}
Console.ReadLine();
}
}
这看起来像是一项家庭作业,所以我只想给你一些提示:
list
变量
例如:
// Create the list
List<int> myListOfIntegers = new List<int>();
// Add some values
myListOfIntegers.Add(2);
myListOfIntegers.Add(5);
myListOfIntegers.Add(3);
// Iterate through the list
foreach(int item in myListOfIntegers)
{
Console.WriteLine("Item Value: " + item);
}
我假设您要打印匹配行和关联行号。目前,您只记得匹配的次数。您在末尾打印的位置是错误的,很可能是-1(除非您的最后一个匹配在最后一行)。如果您不需要对匹配项执行任何其他操作,最简单的方法是在找到匹配项时打印 (另外,您没有关闭要打开的文件)
编辑:拼写问题是什么?您的算法专门计算找到它的行数,而不是实例数。一个单词在一行上可以出现54次,使用IndexOf()方法只能找到一次。此外,您还需要在每次遍历while loopHi Steve时更新位置,因此int position变量计算单词所在的行数?Add应大写dhi Grant,感谢这里的提示。当我在while循环中放置lineNumber以跟踪行时,它表示当前上下文中不存在lineNumber。不确定那里发生了什么。@Gabe您在声明中拼写错误了
lineNumber
。您已将其声明为linenumber
。注意“感谢”中的“N”,在我看到你的评论之前点击一下。我注意到,如果找到这个词,计数总是三。这与txt文件中的行数匹配。这是因为它没有记录找到单词时的实例吗?@Gabe找到了问题,您只是在第一行搜索文本。position=line.IndexOf(wordResponse)代码>行是在当前行中搜索文本的内容。您必须对每一行运行该命令(在执行if(position!=-1)
检查之前)Hi Fai,我已声明使用System.IO;在我的应用程序顶部。我将使用(StreamReader myfile=File.OpenText(fileResponse))放置在哪里?如果我将其放在文件的顶部,则myfile在当前上下文中不存在。我的代码从StreamReader myfile行开始,并替换其余行。”using'是一个C#构造,当您退出右大括号时,它将关闭文件。好的,如果我从myFile行开始使用您的代码,那么它表示myFile和lineNumber在当前上下文中不存在。lineNumber拼写为lineNumber,myFile拼写为myFile。注意c#是区分大小写的。现在修好了
Item Value: 2
Item Value: 5
Item Value: 3
using (StreamReader myFile = File.OpenText(fileResponse))
{
int count = 0; //counts the number of times wordResponse is found.
int lineNumber = 0;
while(!myFile.EndOfStream)
{
string line = myFile.ReadLine();
lineNumber++;
int position = line.IndexOf(wordResponse);
if (position != -1) {
count++;
Console.WriteLine("Match #{0} {1}:{2}", count, lineNumber, line)
}
}
if (count == 0) {
Console.WriteLine("your word was not found!");
} else {
Console.WriteLine("Your word was found " + count + " times!");
}
Console.ReadLine();