C#Dictionary集合的使用
题目:输入一串字符串字母,比如:Welcome to China,比较每个字母出现的次数,不区分大小写。
解决这道题的方法很多。可能一百个人有一百个思路。当时第一眼看到这个题我的思路是:先将接受的一串字符转成小写,写一个for循环,将字符串每一个元素与26英文字母都比一次。但是发现这样很难实现,因为出现的字母和出现的次数怎么对应起来。
什么对应什么,有没发现这就是集合的思想,一个键值对就能搞定。
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// 用户输入一串英文字母,算出每个字母出现的次数,不区分大小写 /// </summary> namespace CollectionLession { class Program { static void Main(string[] args) { var dic = new Dictionary<char, int>(); Console.WriteLine("请输入一句英文"); string str = Console.ReadLine().ToLower(); //接受输入并且转成小写 char[] chs = str.ToCharArray(); for (int i = 0; i < chs.Length; i++) { if (dic.Count > 0) { if (dic.ContainsKey(chs[i])) { dic[chs[i]] += 1; } else dic.Add(chs[i], 1); }//end if else { dic.Add(chs[i], 1); }//end else }//end for //遍历输出一遍集合,但是不输出空格 foreach (var item in dic) { if (item.Key.Equals(' ')) continue; else Console.WriteLine("{0} 出现{1}", item.Key, item.Value); }//end foreach Console.ReadKey(); } } }
这样就搞定了
可能大家在问为什么不用另一个键值对集合Hashtable。
Hashtable是非泛型集合,不妨声明一个Hashtable然后按F12找到Hashtable这个类看看
// // 摘要: // 将带有指定键和值的元素添加到 System.Collections.Hashtable 中。 // // 参数: // key: // 要添加的元素的键。 // // value: // 要添加的元素的值。该值可以为 null。 // // 异常: // T:System.ArgumentNullException: // key 为 null。 // // T:System.ArgumentException: // System.Collections.Hashtable 中已存在具有相同键的元素。 // // T:System.NotSupportedException: // System.Collections.Hashtable 为只读。- 或 - System.Collections.Hashtable 具有固定大小。 [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] public virtual void Add(object key, object value);
Hashtable的key和value是object类型的,而object类型是不能使用运算符的。比如下图
虽然可以使用强制类型转换实现功能,但是还是没有泛型集合Dictionary好用啦
宝宝是那种能不多写一行代码就不愿多写一行代码的猿类
这个代码写了两遍,既然犯了同一个错误
这样写是会把空格都输出的,有时候脑子不好使还真发现不了问题。
因为key是char类型的,所有要用' '符号,“”是字符串类型的时候用的。
如果写成这样就回很容易看出问题,
总之作为一名程序员,要有敏锐的器官。。。一定要对类型较真才行
tip:不懂的代码多按按f12查看是怎么声明的,注释很全,大概就清楚怎么用了