AI智能
改变未来

C#Dictionary实例详解

static void Main(string[] args){//把数字转换成中文字符string inputStr = Console.ReadLine();//123456789//一二三四五//字典<key,value>//声明变量Dictionary<char, string> dic = new Dictionary<char, string>();dic.Add(\'1\', \"一\");dic[\'2\'] = \"二\";dic[\'3\'] = \"三\";//修改一个元素//dic.Add(\'1\',\"壹\");位置已占,会报错dic[\'2\'] = \"贰\";//访问元素//Console.WriteLine(dic[\'2\']);//遍历foreach (var item in dic){//Console.WriteLine(item);if (item.Key == \'1\'){Console.WriteLine(item.Value);}}Console.WriteLine();Dictionary<char, char> dic1 = new Dictionary<char, char>();string num = \"1234567890\";string str = \"一二三四五六七八九零\";for (int i = 0; i < num.Length; i++){dic1[num[i]] = str[i];}for (int i = 0; i < inputStr.Length; i++){//如果用户输入的key不在我们的范围内,会报错//通过ContainsKey判定字典中是否包含了对应的keyif (dic1.ContainsKey(inputStr[i])){Console.Write(dic1[inputStr[i]]);}}Console.WriteLine();//计算字符串中每个字母出现的次数\"Welcome to China! Welcome to HangKang!\"//我能通过字母(char)找到他出现的次数(int)Dictionary<char, int> dic2 = new Dictionary<char, int>();string str1 = \"Welcome to China! Welcome to HangKang!\";for (int i = 0; i < str1.Length; i++){//如果你在字典有了,字典中有了这个字母if (dic2.ContainsKey(str1[i])){//你的值就自增dic2[str1[i]]++;}else{//你的值就是dic2[str1[i]] = 1;}}foreach (var item in dic2){Console.WriteLine(item.Key + \":\" + item.Value);}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C#Dictionary实例详解