C# · 12月 25, 2021

C#中怎样从指定字符串中查找并替换字符串?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
#region
#endregion
namespace Find
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string str = “”;
richText@R_179_2419@1.Text = str;
}
int start = 0;
int count = 0;
/// <summary>
/// 查找字符串
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>

private void find_Click(object sender,EventArgs e)
{
string str1;
str1 = txt_find.Text;
if (start >= richText@R_179_2419@1.Text.Length)
{
Message@R_179_2419@.Show(“以查找到尾部”);
start = 0;
}
else
{
start = richText@R_179_2419@1.Find(str1,start,RichText@R_179_2419@Finds.MatchCase);
if (start == -1)
{
if (count == 0)
{
Message@R_179_2419@.Show(“没有该字符!”);
}
else
{
Message@R_179_2419@.Show(“以查找到尾部!”);
start = 0;
}
}
else
{
start = start + str1.Length;
richText@R_179_2419@1.Focus();
}
}
}
/// <summary>
/// 替换字符串
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void replace_Click(object sender,EventArgs e)
{
richText@R_179_2419@1.Text = richText@R_179_2419@1.Text.Replace(txt_find.Text,txt_replace.Text);
}
/// <summary>
/// 输入查找的字符串
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void txt_find_TextChanged(object sender,EventArgs e)
{
string str1;
str1 = txt_find.Text;
start = 0;
count = 0;
}

}
}

实验结果: