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.模糊搜索
正則表達式簡單使用,讀取數據,使用正則表達式匹配,打印數據
另一種模糊搜索思路:讀取數據,建立倒排序索引,建立一個字典,鍵為單詞,值為行索引