码迷,mamicode.com
首页 > Windows程序 > 详细

C#:统计字符串中每个字符的个数

时间:2017-12-26 00:53:49      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:个数   blog   return   com   oar   src   str   line   string   

具体代码如下:

 1 namespace demo
 2 {
 3     public class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             string str = "hi,good morning.";
 8             Console.WriteLine($"字符串:{str}");
 9             Dictionary<char, int> dic = Count(str);
10             foreach(var c in dic)            
11                 Console.WriteLine($" ‘{c.Key}‘:{c.Value}");            
12             Console.ReadKey();
13         }
14         static Dictionary<char,int> Count(string str)
15         {
16             Dictionary<char, int> dic = new Dictionary<char, int>();
17             char[] chars = str.ToArray();
18             foreach(char c in chars)
19             {
20                 if (dic.ContainsKey(c))
21                     dic[c]++;
22                 else
23                     dic.Add(c, 1);
24             }
25             return dic;
26         }
27     }
28 }

执行结果:
技术分享图片

C#:统计字符串中每个字符的个数

标签:个数   blog   return   com   oar   src   str   line   string   

原文地址:https://www.cnblogs.com/ecake/p/8111614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!