【发布时间】:2015-12-01 05:10:54
【问题描述】:
在控制台应用程序中显示文本文件中的单词时,我需要帮助。例如,我的输入字符串是“the”,代码将读取文本文件并输出包含“the”的单词,例如“The”和“father”。我已经准备好了代码,但它输出了整个句子,包括单词而不是单词本身。代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace QuizTakeHome
{
class Program
{
static void Main(string[] args)
{
string line;
int counter = 0;
Console.WriteLine("Enter a word to search for: ");
string userText = Console.ReadLine();
string file = "Gettysburg.txt";
StreamReader myFile = new StreamReader(file);
int found = 0;
while ((line = myFile.ReadLine()) != null)
{
counter++;
int index = line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase);
if (index != -1)
{
//Since we want the word that this entry is, we need to find the space in front of this word
string sWordFound = string.Empty;
string subLine = line.Substring(0, index);
int iWordStart = subLine.LastIndexOf(' ');
if (iWordStart == -1)
{
//If there is no space in front of this word, then this entry begins at the start of the line
iWordStart = 0;
}
//We also need to find the space after this word
subLine = line.Substring(index);
int iTempIndex = subLine.LastIndexOf(' ');
int iWordLength = -1;
if (iTempIndex == -1)
{ //If there is no space after this word, then this entry goes to the end of the line.
sWordFound = line.Substring(iWordStart);
}
else
{
iWordLength = iTempIndex + index - iWordStart;
sWordFound = line.Substring(iWordStart, iWordLength);
}
Console.WriteLine("Found {1} on the sentence: {1} on line number: {0}", counter, sWordFound, line);
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);
}
}
}
输出如下:
有人可以帮忙吗?
【问题讨论】:
-
好吧,您逐行读取文件,并在整个行中搜索匹配项。您应该逐字阅读文件,或拆分行,然后执行 IndexOf
-
你觉得你能告诉我这是怎么做的吗?
-
嗯,首先你需要确定什么是“单词”。单词可以用空格分隔,也可以用其他字符、逗号、分号等分隔。我们在这里看什么样的输入?
-
我的输入字符串是“the”。我已准备好一切,但我的 sWordFound 输出的是“the”,但之后是句子的其余部分。我只需要剪掉“the”之后的部分。