前言:
实现了一个简单的文本替换应用程序的功能,用户可以通过该程序选择一个文本文件,然后输入要查找和替换的文本,最后执行查找和替换操作
一、所需控件
二、源码展示
private void button1_Click(object sender, EventArgs e)
{
// 打开文件选择对话框
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// 将选择的文件路径显示在txtBoxFile文本框中
txtBoxFile.Text = openFileDialog1.FileName;
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
// 获取要搜索的文本
string search = txtBoxSearch.Text.Trim();
if (!string.IsNullOrEmpty(search))
{
// 获取要搜索的文件路径
string fileName = txtBoxFile.Text.Trim();
using (TextReader tr = File.OpenText(fileName))
{
// 读取文件内容
string content = tr.ReadToEnd();
// 调用CountNumber方法计算搜索结果数量
int count = CountNumber(content, search);
// 显示搜索结果数量
DisplaySearchCount(count);
}
}
}
void DisplaySearchCount(int count)
{
// 在lblSearchResult标签中显示搜索结果数量
lblSearchResult.Text = "共查找到:\r\n" + count.ToString() + "\r\n个结果。";
}
void DisplayReplaceCount(int count)
{
// 在lblReplaceResult标签中显示替换结果数量,同时也更新搜索结果数量
DisplaySearchCount(count);
lblReplaceResult.Text = "共替换:\r\n" + count.ToString() + "\r\n行。";
}
private int CountNumber(string father, string son)
{
// 判断是否有相同字符串
if (father.Contains(son))
{
// 用一个字符串储存被替换后的整个字符串
string strReplaced = father.Replace(son, "");
// 两个字符串的长度差值 / 被替换掉的字符串单位长度
return (father.Length - strReplaced.Length) / son.Length;
}
// 如果没有相同字符串,返回0个结果
return 0;
}
private void button2_Click(object sender, EventArgs e)
{
// 与btnSearch_Click方法类似,执行搜索操作并显示结果数量
string search = txtBoxSearch.Text.Trim();
if (!string.IsNullOrEmpty(search))
{
string fileName = txtBoxFile.Text.Trim();
using (TextReader tr = File.OpenText(fileName))
{
string content = tr.ReadToEnd();
int count = CountNumber(content, search);
// 显示查找到的结果数量
DisplaySearchCount(count);
}
}
}
private int replacementCount = 1; // 初始替换计数为1
private void button3_Click(object sender, EventArgs e)
{
// 获取要搜索和替换的文本
string search = txtBoxSearch.Text;
string replace = txtBoxReplace.Text;
if (!string.IsNullOrEmpty(search))
{
string fileName = txtBoxFile.Text.Trim();
string content, result;
using (TextReader tr = File.OpenText(fileName))
{
content = tr.ReadToEnd();
// 调用CountNumber方法计算搜索结果数量
result = content.Replace(search, replace);
}
// 写入文件
using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
Byte[] info = new UTF8Encoding(true).GetBytes(result);
fs.Write(info, 0, info.Length);
}
// 计算替换后的结果数量并显示
int count = CountNumber(content, search);
DisplayReplaceCount(count);
}
}
demo下载:https://download.csdn.net/download/m0_55074196/88365319