winform 查找替换字符串
时间: 2023-12-15 17:06:49 浏览: 41
以下是Winform中查找替换字符串的方法:
1.使用RichTextBox控件的Find方法查找指定字符串,并返回第一个字符在控件内的位置。
```csharp
// 查找指定字符串
int index = richTextBox1.Find("要查找的字符串");
// 如果找到了,将光标移动到该位置
if (index >= 0)
{
richTextBox1.Select(index, "要查找的字符串".Length);
richTextBox1.ScrollToCaret();
}
```
2.使用Replace方法替换指定字符串。
```csharp
// 替换指定字符串
richTextBox1.Text = richTextBox1.Text.Replace("要替换的字符串", "替换后的字符串");
```
3.使用自定义方法CountNumber实现查找并替换指定字符串。
```csharp
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;
}
// 查找并替换指定字符串
string str = richTextBox1.Text;
string oldStr = "要查找的字符串";
string newStr = "替换后的字符串";
int count = CountNumber(str, oldStr);
for (int i = 0; i < count; i++)
{
int index = str.IndexOf(oldStr);
str = str.Remove(index, oldStr.Length).Insert(index, newStr);
}
richTextBox1.Text = str;
```