要求:输入英文单词能够给出一个反馈;
准备工作:有一个英汉对应的txt文件;
代码实现:
<span style="font-size:18px;">namespace _07英汉翻译
{
class Program
{
static void Main(string[] args)
{
//读文件
string path = @"E:\C#程序\20121106解决方案\07英汉翻译\英汉词典TXT格式.txt";//自己存放的路径
string[] text = File.ReadAllLines(path ,Encoding.Default );
Dictionary<string, string> myDic = new Dictionary<string, string>();
//遍历里面的英语和汉语,把英文作为key,中文作为value
for (int i = 0; i < text.Length ; i++)
{
string[] strText = text[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string english = strText[0];
string chinese = "";
for (int j = 1; j < strText .Length ; j++)
{
chinese +=strText [j];//把这个单词后面所有的中文加到一起
}
if (!myDic.ContainsKey(strText[0]))
{
myDic.Add(english,chinese);
}
else
{
myDic[english ]+=chinese ;
}
}
Console .WriteLine("请输入英文单词");
string str=Console .ReadLine ();
if (myDic.ContainsKey(str))
{
Console .WriteLine (myDic[str]);
}
else
{
Console .WriteLine ("字典中没有这个单词");
}
Console .ReadKey ();
}
}
}</span>
实现效果:
总结:Dictionary<TKey,Tvalue>用法:默认提供的命名空间System.Collections.Generic,TKey:字典中的键的类型。TValue:字典中的值的类型,它们是一对存在的,用法类似于Hahtable.