文章目录
概述
- 哈希表(Hash table,也叫散列表),是根据关键码值(Key
value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。 - 给定表M,存在函数f(key),对任意给定的关键字值key,代入函数后若能得到包含该关键字的记录在表中的地址,则称表M为哈希(Hash)表,函数f(key)为哈希(Hash)
函数。
哈希表(HashTable)
- 添加数据,以键(key)值(value)对形式存储
- 键值对均是object类型
- 键值对中的键是为了找数据的,必须存在,但不能重复存在
- 是一种无序的结构
键值对的存储、输出
Hashtable ht = new Hashtable();
ht.Add("哈哈", "001");//存储键值对
ht.Add("嘿嘿", 003);
ht.Add(new Person("小李", '男', 22), 222);//存储类键值对
Console.WriteLine("{0},{1}","哈哈",ht["哈哈"]);//根据某一键,输出对应的值
foreach (object st in ht.Keys)//foreach循环:输出键值对
{
Console.WriteLine("key{0}=====value{1}",st,ht[st]);
}
Console.ReadKey();
哈希表(HashTable)方法
ht.Clear();//清除所有元素
ht.Contains("哈哈");//判断是否包含特定键
ht.ContainsKey("嘿嘿");//判断是否包含特定键
ht.ContainsValue(003);//判断是否包含特定值
int num = ht.Count;//获取键值对数量
ht.Remove(003);//移除特定键,值也一起移除
ht.Values() //获取值,不单独使用
简繁体转换
private const String jtz = "一二三四五六七八九十";
private const String ftz = "壹贰叁肆伍陆柒捌玖拾";
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
for (int i = 0; i < jtz.Length ; i++)//将简繁体字添加到哈希表中
{
ht.Add(jtz[i], ftz[i]);
}
string text = "一二三四五六七八九十哈哈哈哈";
for (int i = 0; i < text.Length ; i++)//遍历字符串text
{
if (ht.Contains(text[i ]))
{
Console.Write(ht[text[i]]);
}
else
{
Console.Write(text[i]);
}
}
Console.ReadKey();
}
火星文翻译
private const String mars = "项工页 张弓长 从人人 陈耳东 轩车干 旭九日 杜木土 胡古月";
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
string[] strs = mars.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//去除空格,并转换成字符串
for (int i = 0; i < strs.Length; i++)//遍历字符串
{
if (!ht.Contains(strs[i]))//哈希表中不包含字符串中的火星文就添加键值对
{
ht.Add(strs[i][0], strs[i].Substring(1));
}
}
string text = "项张从陈轩旭杜哈哈哈哈";
for (int i = 0; i < text.Length; i++)//遍历text字符串
{
if (ht.Contains(text[i]))//如果哈希表中包含text中的键,就转换为值
{
Console.Write(ht[text[i]]);
}
else
{
Console.Write(text[i]);
}
}
}
Dictionary
Dictionary和哈希表很相似
- 元素是无序的。
- 以键值对的形式存储值
- 很多方法与HashTable相似
Dictionary添加数据
//<>中写数据类型
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("哈哈", "hh");
dic.Add("嘿嘿", "hh");
dic.Add("哟哟", "yy");
foreach (string str in dic.Keys )
{
Console.WriteLine("{0}---{1}",str,dic[str]);
}
Console.ReadKey();