计算字符串中每个字符出现的次数

 1  /// <summary>
 2         /// 计算每个字符出现的次数且打印
 3         /// </summary>
 4         /// <param name="str"></param>
 5         public void CharCount(string str)
 6         {
 7             Dictionary<char, int> dicCount = new Dictionary<char, int>();
 8             str = str.ToLower();
 9             foreach (char item in str.ToCharArray())
10             {
11                 if (!Char.IsLetter(item))  
12                     continue;
13                 if (!dicCount.ContainsKey(item))
14                 {
15                     dicCount.Add(item, 1);
16                 }
17                 else
18                 {
19                     dicCount[item]++;
20                 }
21             }
22 
23             foreach (var item in dicCount.Keys)
24             {
25                 Console.WriteLine("字符{0}:出现{1}次",item,dicCount[item]);
26             }
27         }

 

posted @ 2013-11-02 23:55  徽州猿人  阅读(248)  评论(0编辑  收藏  举报