c#中,怎样逐行读取.txt里面的汉字,并统计每行汉字的出现的次数

如题所述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
               
                string[] Lines=File.ReadAllLines("C:\\Demo.txt");
                for(int i=0;i<Lines.Length;i++) 
                {
                    Dictionary<string, int> result = new Dictionary<string, int>();
                    foreach (char chr in Lines[i].ToCharArray()) 
                    {
                        if (result.ContainsKey(chr.ToString()))
                            result[chr.ToString()] += 1;
                        else
                            result.Add(chr.ToString(),1);
                    }
                    string end=string.Format("第{0}行:",i+1);
                    
                    foreach(KeyValuePair<string, int> kvp in result)
                    {
                        end+=string.Format("[{0}]字出现了{1}次,\t",kvp.Key,kvp.Value);
                    }
                    Console.WriteLine(end);
                }
            }
            catch (Exception ex) 
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }
}

控制台的!!

自己在C盘建立一个Demo.txt 文件,然后在里面输入汉字保存,然后把代码复制到你的工程中去编译执行看看,仅供参考号!!

温馨提示:答案为网友推荐,仅供参考
相似回答