具体代码如下:
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 }
执行结果: