C#统计字符出现次数

计算类:

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

namespace CalCount
{
    class CalUtil
    {

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

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

程序输出:


1.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,286评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,874评论 18 399
  • 前言 《四柱特训班讲义》一书,是笔者根据2003年春举办的四柱特训班讲课记录的基础上整理出来的。它是以《四柱详真》...
    小狐狸娃娃阅读 12,649评论 1 29
  • 白粥可温阅读 201评论 1 2
  • 心理剧小知识 1、 心理剧的创始人是雅各布·列维·莫雷诺,他1889年出生于一个西班牙系犹太人血统的家庭。1921...
    菲乐阅读 4,024评论 0 8