Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - Replace all text in a rich text box

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...