Skip to content

Instantly share code, notes, and snippets.

@abdulateef
Last active August 5, 2016 10:32
Show Gist options
  • Save abdulateef/d0aeb0615aef6ecf3ba5fcbaf04d7fe5 to your computer and use it in GitHub Desktop.
Save abdulateef/d0aeb0615aef6ecf3ba5fcbaf04d7fe5 to your computer and use it in GitHub Desktop.
how to count the occurrence of a word in a text file using c#
public static void WordCount(string word, string path)
{
int index;
int occurrence = 0;
try
{
StreamReader reader = new StreamReader(path);
using(reader)
{
string line = reader.ReadLine();
while (line != null)
{
index = line.IndexOf(word);
while (index != -1)
{
occurrence++;
index = line.IndexOf(word,(index + 1));
}
line = reader.ReadLine();
}
Console.WriteLine("the word {0} occours in {1} times", word, occurrence);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment