Last active
August 5, 2016 10:32
-
-
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#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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