统计C盘(含子目录)所有文本文件(*.txt)中出现单词this、word 的个数,速求代码

解决方案 »

  1.   

    首先,你要确保你的程序拥有访问C盘的权限。
                Stack<string> pathes = new Stack<string>();
                List<string> txts = new List<string>();
                pathes.Push(@"C:\");
                //获取所有txt文件
                while (pathes.Count > 0)
                {
                    try
                    {
                        string folder=pathes.Pop();
                        foreach (string el in Directory.GetDirectories(folder))
                            pathes.Push(el);
                        foreach (string ek in Directory.GetFiles(folder, "*.txt"))
                            txts.Add(ek);
                    }
                    catch { }
                }
                //查找内容
                int thisCount = 0;
                int wordCount = 0;            foreach (string el in txts)
                {
                    try
                    {
                        using (StreamReader reader = new StreamReader())
                        {
                            string content = reader.ReadToEnd();
                            thisCount += Regex.Matches(content, @"( |[^A-Za-z\d])this( |[^A-Za-z\d])").Count;
                            wordCount += Regex.Matches(content, @"( |[^A-Za-z\d])word( |[^A-Za-z\d])").Count;
                        }
                    }
                    catch { }
                }
            }
    正则表达式可以再考虑下。
      

  2.   

    #include <iostream>
    using namespace std;
    int main()
    {
    FILE *fin = fopen("c:\\Mydir\\data.txt","r");
    FILE *fout = fopen("c:\\Mydir\\res.txt","w");
    char ch;
    int cnt=0;
    while ((ch=fgetc(fin))!=1)
    {
    if (ch=='$')
    cnt++;
    }
    fprintf(fout,"%d\n",cnt);
    return 0;
    }和你那个实现的功能类似,你改一下应该可以的