持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第15天,点击查看活动详情
1、功能介绍
如图所示我们在上面的文本框写入单词,点击翻译,在下面的文本框就会显示出汉语意思。
2、代码实现
首先我们用的工具是vs2017 Windows窗体开发,使用的是C#语言。其次我们要有一个.txt文件的单词本,大家可以自己随意写几个单词作为案例。格式如下:(每行一个单词)
每一个按钮包括整个窗体都是类创建的对象,双击这些按钮,VS2017 会自动为我们书写对应的函数,我们只需要在{}中写代码就可以了。
2、读文件
添加using System.IO;中的File类读取文件内容,并将其赋给字符串数组。
string[] strs = File.ReadAllLines(@"C: \Users\hewen\Desktop\dic.txt", Encoding.Default);
创建字典
使用字典创建一对<Key,Value>用于记录每行字符串的汉语意思和英文单词。
Dictionary<string, string> dic = new Dictionary<string, string>();
3、分割字符串
.txt文件中的每一行都是是个含有空格的字符串,我们需要用string的Split函数将其分割,并分别赋给字典的Key和Value。
string[] substr = item.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
//以空格为标志分割字符串
//RemoveEmptyEntries可以解决大部分的乱码问题。
string key = substr[0];
string value = substr[1];
4、寻找汉语意思
object类是所有类的父类,用它可以接收文本框一种的英文单词。
private void Form1_Load(object sender,EventArgs e)//双击窗体,VS2017自动编写。
{
string[] strs = File.ReadAllLines(@"C: \Users\hewen\Desktop\dic.txt", Encoding.Default);
foreach (string item in strs)
{
string[] substr = item.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//打开文件
string key = substr[0];
string value = substr[1];
if(dic.ContainsKey(key))
{
dic[key] += value;
}
else
{
dic.Add(key, value);
}
}
}
在文本框2中展示汉语
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = dic[textBox1.Text];
}
3、完整代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//"C:\Users\hewen\Desktop\dic.txt"
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
Dictionary<string, string> dic = new Dictionary<string, string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender,EventArgs e)
{
string[] strs = File.ReadAllLines(@"C: \Users\hewen\Desktop\dic.txt", Encoding.Default);
foreach (string item in strs)
{
string[] substr = item.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string key = substr[0];
string value = substr[1];
if(dic.ContainsKey(key))
{
dic[key] += value;
}
else
{
dic.Add(key, value);
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = dic[textBox1.Text];
}
}
}
4、总结
neirongcucao,duoduobaohan.