Click here to Skip to main content
15,847,902 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am having a text file, I need to read all the contents in it and count all the occurrences of a particular word using c#

How to do this
ZurdoDev 26-Mar-14 8:05am    
Start off by using the File class, and then let us know where you are stuck.

There are a huge number of ways to do this: this tip shows a number of them for newline characters: Counting Lines in a String[^] - but the principle is very much the same for whole words.

Probably the way you want to look is with a regex:
string text = File.ReadAllText(@"D:\Temp\MyText.txt").ToLower();
int hellos = Regex.Matches(text, @"\bhello\b").Count;

returns the number of times "hello" appears in the file as a complete word.
Share this answer
first find all the words in the sentence( use space to find the words) and keep them in array and again loop through the array to find the matching words. you may need multiple loops. you can make it.. come on :)
Share this answer
lukeer 26-Mar-14 8:18am    
Or a List<string> instead of array.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900