C#统计字符出现次数

计算类:

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

namespace CalCount
{
    class CalUtil
    {

        public static void outputDict(Dictionary Dict)
        {
            foreach(KeyValuePair pair in Dict)
            {
                Console.WriteLine(new string(new char[]{pair.Key}) + ": "+ pair.Value);
            }
        }
        public static Dictionary getCount(string calStr)
        {
            if (calStr == null || calStr.Length == 0)
            {
                throw new Exception("Can't cal empty string!!");
            }
            Dictionary retDict = new Dictionary();

            foreach (char c in calStr)
            {
                int oldValue;
                retDict.TryGetValue(c,out oldValue);
                retDict[c] = ++oldValue;
            }
            return retDict;
        }
    }
}

主程序类:

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

namespace CalCount
{
    class Program
    {
        static void Main(string[] args)
        {
            CalUtil.outputDict(CalUtil.getCount("hello,World!!!"));
            Console.ReadKey();
        }
    }
}

程序输出:


C#统计字符出现次数_第1张图片
1.png

你可能感兴趣的:(C#统计字符出现次数)