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


具体代码如下:

 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 }

执行结果:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM