C#窗体实现数据录入与模糊搜索小案例
记录一下
主要代码
private void button1_Click(object sender, EventArgs e){string name = textBox1.Text;string hometown = textBox4.Text;string school = textBox6.Text;string sex = textBox5.Text;string lat = textBox3.Text;string log = textBox2.Text;if (saveFileDialog1.ShowDialog() == DialogResult.OK){string[] lines = File.ReadAllLines(saveFileDialog1.FileName, Encoding.UTF8); // 如果你需要逐行搜索string str=String.Join("\n",lines);str += "\n" + name + "," + sex + "," + hometown + "," + school + "," + lat + "," + log + "\n";StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);sw.Write(str);sw.Close();MessageBox.Show("保存成功!!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);}}private void button2_Click(object sender, EventArgs e){string str=textBox7.Text;string searchTerm = str; // 正则表达式示例,这里仅匹配独立的“关键字”Regex regex = new Regex(searchTerm, RegexOptions.IgnoreCase);if (openFileDialog1.ShowDialog() == DialogResult.OK){string[] lines = File.ReadAllLines(openFileDialog1.FileName, Encoding.UTF8); // 如果你需要逐行搜索foreach (var line in lines){Match match = regex.Match(line);if (match.Success){richTextBox1.Text = line+"\n";MessageBox.Show("找到啦", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);}}}}
实现思路:
1.数据录入
取textbox数据,打开存储文件,读取数据,添加一行数据,再重新存储数据
2.模糊搜索
正则表达式简单使用,读取数据,使用正则表达式匹配,打印数据
另一种模糊搜索思路:读取数据,建立倒排序索引,建立一个字典,键为单词,值为行索引