搜索和替换文本,例如记事本

时间:2018-07-30 08:05:53

标签: c# replace

我试图在自己的记事本版本中进行搜索和替换功能。它可以工作,但是只在第一行中搜索和替换。如何在整个记事本(txtNotepad)中进行搜索和替换,这样替换过程会更加有效?

到目前为止,我的代码:

private void metroButton4_Click(object sender, EventArgs e)
{
    int locaction;
    string myString, search, replace;

    myString  = txtNotepad.Text;
    search    = txtSearchFor.Text.Trim();
    replace   = txtReplaceWith.Text.Trim();
    locaction = txtNotepad.Text.IndexOf(search);

    if (locaction == -1)
    {
        MetroFramework.MetroMessageBox.Show(this, "String not found", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
    {
        txtNotepad.Text = myString.Remove(locaction, search.Length).Insert(locaction, replace);
    }
}

2 个答案:

答案 0 :(得分:4)

为什么不简单使用Replace中的method string

  

返回一个新字符串,在该字符串中,当前实例中所有出现的指定字符串都被另一个指定字符串替换。

txtNotepad.Text = myString.Replace(search, replace);

答案 1 :(得分:2)

您可以在c#中使用字符串替换方法。

例如:

txtNotepad.Text = myString.Replace(search,replace);

将所有出现的“ 搜索”替换为“ 替换”。