peter peter - 1 month ago 8
C# Question

c# count a specific word happen times in a txt file

static void Main(string[] args)
{
StreamReader oReader;
if (File.Exists(@"C:\cmd.txt"))
{
Console.WriteLine("IMAGE");
string cSearforSomething = Console.ReadLine().Trim();
oReader = new StreamReader(@"C:\cmd.txt");
string cColl = oReader.ReadToEnd();
string cCriteria = @"\b" + cSearforSomething + @"\b";
System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex(cCriteria, RegexOptions.IgnoreCase);



int count = oRegex.Matches(cColl).Count;
Console.WriteLine(count.ToString());
}
Console.ReadLine();
}


I cannot calculate the string "IMAGE" happen times in my file? Is my code wrong?

Answer

Try this code

public static void Main()
{
    var str = File.ReadAllText(@"C:\cmd.txt");
    var searchTerm = "IMAGE";

    var matches = Regex.Matches(str, @"\b" + searchTerm + @"\b", RegexOptions.IgnoreCase);

    Console.WriteLine(matches.Count);
    Console.ReadLine();            
}