在日常开发或者文本处理工作中,我们经常会遇到需要批量处理字符串的场景,比如替换特定字符、提取符合规则的内容、调整文本格式等,手动操作不仅耗时还容易出错。这时候自己开发一款简单的C#字符串处理小工具就能大幅提升效率。

工具核心功能设计
这款小工具主要实现以下常用字符串处理功能:
- 批量文本替换:支持输入待替换内容和替换后内容,对目标文本进行全局替换
- 正则提取:通过正则表达式提取文本中符合规则的内容,比如提取所有手机号、邮箱地址
- 格式调整:去除文本首尾空格、去除空行、统一换行符格式
- 编码转换:支持常见字符串编码之间的转换,比如UTF8和GBK互转
界面搭建
我们使用WinForms搭建简单的操作界面,主要包含文本输入区域、功能选择区域、参数输入区域和结果展示区域。核心控件布局如下:
| 控件类型 | 控件名称 | 用途说明 |
|---|---|---|
| TextBox | txtInput | 输入待处理的原始字符串 |
| TextBox | txtOutput | 展示处理后的字符串结果 |
| ComboBox | cbFunction | 选择要使用的字符串处理功能 |
| Button | btnProcess | 触发字符串处理操作 |
核心功能代码实现
文本替换功能
文本替换是最基础的功能,使用C#内置的string.Replace方法即可实现,核心代码如下:
// 文本替换处理方法
private string ReplaceText(string input, string oldStr, string newStr)
{
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldStr))
{
return input;
}
// 执行替换操作
return input.Replace(oldStr, newStr);
}正则提取功能
正则提取需要用到System.Text.RegularExpressions命名空间下的Regex类,以下示例是提取文本中的所有邮箱地址:
using System.Text.RegularExpressions;
// 正则提取邮箱地址
private List<string> ExtractEmail(string input)
{
List<string> result = new List<string>();
if (string.IsNullOrEmpty(input))
{
return result;
}
// 邮箱正则规则
string pattern = @"[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
result.Add(match.Value);
}
return result;
}格式调整功能
去除文本首尾空格和空行的实现代码如下:
// 去除文本首尾空格和空行
private string TrimText(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
// 按行分割文本
string[] lines = input.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
List<string> validLines = new List<string>();
foreach (string line in lines)
{
// 去除每行首尾空格,跳过空行
string trimmedLine = line.Trim();
if (!string.IsNullOrEmpty(trimmedLine))
{
validLines.Add(trimmedLine);
}
}
// 重新拼接为文本
return string.Join(Environment.NewLine, validLines);
}功能触发逻辑
在按钮点击事件中根据选择的功能调用对应的处理方法,核心逻辑如下:
private void btnProcess_Click(object sender, EventArgs e)
{
string input = txtInput.Text;
string selectedFunc = cbFunction.SelectedItem.ToString();
string output = string.Empty;
switch (selectedFunc)
{
case "文本替换":
// 这里可以获取界面输入的替换参数
output = ReplaceText(input, "待替换内容", "替换后内容");
break;
case "正则提取邮箱":
List<string> emails = ExtractEmail(input);
output = string.Join(Environment.NewLine, emails);
break;
case "去除空格空行":
output = TrimText(input);
break;
default:
output = input;
break;
}
txtOutput.Text = output;
}扩展建议
这款基础的小工具还可以根据需求进一步扩展,比如增加批量文件处理功能,支持导入txt文件批量处理内容;增加处理规则保存功能,把常用的处理参数保存下来下次直接使用;还可以增加字符串加密解密、Base64编码转换等更多实用功能,让工具更贴合实际使用场景。