c#计算特定单词在TXT文件中出现的次数

本文关键字:文件 TXT 计算 单词 | 更新日期: 2023-09-27 18:14:51

    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();
    }

我不能计算字符串"图像"发生的时间在我的文件?我的代码错了吗?

c#计算特定单词在TXT文件中出现的次数

试试这个代码

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();            
}  

根据https://msdn.microsoft.com/en-us/library/az24scfc.aspx, "'b"匹配退格。这可以解释为什么没有匹配正则表达式。

using System;使用包含;

ConsoleApplication8

名称空间{类项目{

    static void Main(string[] args)
    {
        string cColl = System.IO.File.ReadAllText(@"C:'some.txt");
        //string cColl = "This is similar, similar, similar, similar, similar, similar";
        Console.WriteLine(cColl);
        string cCriteria = @"'b" + "similar" + @"'b";
        Regex oRegex = new Regex(cCriteria, RegexOptions.IgnoreCase);
        int count = oRegex.Matches(cColl).Count;
        Console.WriteLine(count.ToString());
        Console.ReadLine();
    }


}

}