I need help in displaying the word from a text file in a Console Application. For example, my input string would be "the" and the code will read through the text file and output the words containing "the" such as "The" and "father". I have the code ready but its outputting the entire sentence including the word rather than the word itself. The code looks like this:
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);
}
}
}
And the output looks like:
Can anybody help?