Replace all text in a rich text box

扶醉桌前 提交于 2019-12-18 09:08:06

问题


I have a problem while trying to replace all text matching a particular word in a rich text box. This is the code i use

    public static void ReplaceAll(RichTextBox myRtb, string word, string replacer)
    {
        int index = 0;

        while (index < myRtb.Text.LastIndexOf(word))
        {
            int location = myRtb.Find(word, index, RichTextBoxFinds.None);
            myRtb.Select(location, word.Length);
            myRtb.SelectedText = replacer;
            index++;
        }
        MessageBox.Show(index.ToString());
    }

    private void btnReplaceAll_Click(object sender, EventArgs e)
    {
        Form1 text = (Form1)Application.OpenForms["Form1"];
        ReplaceAll(text.Current, txtFind2.Text, txtReplace.Text);
    }

This works well but i have noticed a little malfunction when i try to replace a letter with itself and another letter.

For example i want to replace all the e in Welcome to Nigeria with ea.

This is what i get Weaalcomeaaaaaaa to Nigeaaaaaaaaaaaaaaria.

And the message box shows 23 when there are only three e. Pls what am i doing wrong and how can i correct it


回答1:


Simply do this:

yourRichTextBox.Text = yourRichTextBox.Text.Replace("e","ea");

If you want to report the number of matches (which are replaced), you can try using Regex like this:

MessageBox.Show(Regex.Matches(yourRichTextBox.Text, "e").Count.ToString());

UPDATE

Of course, using the method above has expensive cost in memory, you can use some loop in combination with Regex to achieve some kind of advanced replacing engine like this:

public void ReplaceAll(RichTextBox myRtb, string word, string replacement){
   int i = 0;
   int n = 0;
   int a = replacement.Length - word.Length;
   foreach(Match m in Regex.Matches(myRtb.Text, word)){          
      myRtb.Select(m.Index + i, word.Length);
      i += a;
      myRtb.SelectedText = replacement;
      n++;
   }
   MessageBox.Show("Replaced " + n + " matches!");
}


来源:https://stackoverflow.com/questions/18905193/replace-all-text-in-a-rich-text-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!