Reputation:
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
Upvotes: 2
Views: 8728
Reputation: 63317
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());
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!");
}
Upvotes: 7