-1

I am trying to search for a word in a text file that I am reading into C#.

As of right now it keeps on showing the word is at line zero when it is not.

What am I doing wrong in the code?

Also, how would I make it count the word that I search for so that it can show the amount of occurrence?

        string line;
        int counter = 0;

        Console.WriteLine("Enter a word to search for: ");
        var text = Console.ReadLine();

        string file = "newfile.txt";
        StreamReader myFile = new StreamReader(file);

        Console.WriteLine("\n");

        while ( (line = myFile.ReadLine()) != null )
        {
            if(line.Contains(text))
            {
                break;
            }
            counter++;
        }
        Console.WriteLine("Line number: {0}", counter);

        myFile.Close();
        Console.ReadLine();
Lebron Jamess
  • 109
  • 2
  • 12

1 Answers1

1

To solve the other part of your question... "how to find all the occurrences".

Add a new variable to store the number found:

int found = 0;

Rework your while loop to not break out - but report where you found it and increase your found count. After the while loop summarise your findings.

while ((line = myFile.ReadLine()) != null)
{
    // Increment the line counter first so it's not zero indexed
    counter++;

    // If it contains the text tell us what line and increase found
    // Note: No need to break out of the code since we want to find all of them this time
    if (line.Contains(text))
    {
        Console.WriteLine("Found on line number: {0}", counter);
        found++;
    }
}

Console.WriteLine("A total of {0} occurences found", found);
Robert Pilcher
  • 376
  • 1
  • 10
  • Oh, nice that was what I was coding towards. One question, is there a way to find a word and how much it occurs like the letter "the' appearing in the word their? – Lebron Jamess Nov 28 '15 at 02:04
  • How would i make it so that it is not case sensitive as well? – Lebron Jamess Nov 28 '15 at 02:16
  • You could probably code around all the possible for finding if this is a complete word... like check that there's a space or punctuation following the match (use `IndexOf()` and `Substring()`). Similarly you can modify the case of the string with `ToLower()` - but it begins to get complicated. I'd recommend that you take a look at what RegEx can do for you... – Robert Pilcher Nov 28 '15 at 02:19
  • I'm trying Regex, but there is a red underline under it. Is there any extra thing I needed to add to use it? – Lebron Jamess Nov 28 '15 at 02:30
  • Add `using System.Text.RegularExpressions;`. There are loads of RegEx examples out there... try [this URL](http://stackoverflow.com/questions/1209049/c-regex-match-whole-words) or [this set of examples](http://www.dotnetperls.com/regex-match) for some general pointers. – Robert Pilcher Nov 28 '15 at 02:35