C# Dictionary 用法 -- 查找字符串中同一个字符出现次数
string str ="welcome to bejing , hello china,jiyou wuhan"; Dictionary<char, int> dict = new Dictionary<char, int>(); for (int i = 0; i < str.Length; i++) { if (str[i] == ' ') { continue; } if (dict.ContainsKey(str[i])) { dict[str[i]]++; } else { dict[str[i]] = 1; } } foreach (KeyValuePair<char,int> k in dict) { Console.WriteLine("字符:{0} 共出现{1}次",k.Key,k.Value); } Console.ReadKey();
运行结果: