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

Posted ecake

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

执行结果:

以上是关于C#:统计字符串中每个字符的个数的主要内容,如果未能解决你的问题,请参考以下文章