本篇介绍字典。Dictionary。
主要原理请参考下面的博客:
https://blog.csdn.net/exiaojiu/article/details/51252515
https://www.cnblogs.com/xiaomowang/p/12405639.html
https://blog.csdn.net/zhaoguanghui2012/article/details/88105715
其对应《数据结构》中的哈希表。
用字典解决字符串出现次数问题。
1、问题描述
输入有多行,第一行是一个整数x,表明后面还有x行,每一行是一个字符串。
要求输出:每个字符串及其出现的次数。
2、参考代码
static void Main()
{
int x = ReadInt();//输入共有多少行
Dictionary<string, int> color_count = new Dictionary<string, int>();
for (int i = 0; i < x; i++)
{
string color = Console.ReadLine();
if (color_count.ContainsKey(color))
{
color_count[color] += 1;
}
else
{
color_count[color] = 1;
}
}
foreach (KeyValuePair<string, int> kvp in color_count)
{
Console.WriteLine("{0}出现了{1}次", kvp.Key, kvp.Value);
}
}
static int ReadInt()
{
int x = int.Parse(Console.ReadLine());
return x;
}
注:本程序由LIU MING XUN同学提供。