Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count a specifc word in a text file in C#

Tags:

c#

If i got a text file

"dont run if you cant hide, or you will be broken in two strings, your a evil man"

and i want to count how many times the word you is in the text file, and put that value in to a int variable.

how do i go about doing somthing like that?

like image 222
Darkmage Avatar asked Dec 07 '25 08:12

Darkmage


2 Answers

To say it with a Regex...

Console.WriteLine((new Regex(@"(?i)you")).Matches("dont run if you cant hide, or you will be broken in two strings, your a evil man").Count)

or if you need the word you as stand-alone

Console.WriteLine((new Regex(@"(?i)\byou\b")).Matches("dont run if you cant hide, or you will be broken in two strings, your a evil man").Count)

Edit: Replaced \s+you\s+ with (?i)\byou\b for the sake of correctness

like image 137
Scoregraphic Avatar answered Dec 08 '25 21:12

Scoregraphic


string s = "dont run if you cant hide, or you will be broken in two strings, your a evil man";
var wordCounts = from w in s.Split(' ')
                 group w by w into g
                 select new { Word = g.Key, Count = g.Count() };

int youCount = wordCounts.Single(w => w.Word == "you").Count;
Console.WriteLine(youCount);

Ideally punctuation should be ignored. I'll let you handle a messy detail like that.

like image 29
jason Avatar answered Dec 08 '25 21:12

jason