Gideon
Gideon

Reputation: 2014

Find/Replace function RichTextBox

I want to make a find and a find & replace function for my RichTextBox. So far I've found out that the .Find() function comes in quite handy, but I can't think of a good way to let it skip to the next word in the textbox.

So far I have this:

BeginIndex = txtDocument.Find(str, BeginIndex + WordLength, RichTextBoxFinds.None);
WordLength = str.Length;

BeginIndex is a variable that is public and starts out as 0, same as WordLength. This way it will start looking at the first character, and the next time it won't find the same one. There is a big malfunction though, let me try to describe it: "Hello blablab hello blablaal balbalbla hello blabla" If I would look for "hello" in this sentence, it will select the first hello, then the second, then the third, then the third again. After that it will just find the second and the third over and over. Because WordLength is still > 0.

So I need a new way to tell the Find() method that its not allowed to find the one already found, but move on, and when the last one is found, go back to the first. Is there a more clean and better way to do this?

Edit: Its almost fixed, I use this now:

BeginIndex = txtDocument.Find(str, BeginIndex, RichTextBoxFinds.None);

if(BeginIndex == -1) {
    BeginIndex = 0;
    SearchString(str, heelwoord, casesensitive);
}

BeginIndex += str.Length;

Now, this loops quite nice, instead of calling itself (int the if) I can also make a MessageBox that says something like "End is reached!". But if it finds nothing, it gives me an error. I use the function with 2 checkboxes, one that does MatchCase, and one that does WholeWord, but when I look for 'a' in "asdasdasd" and check WholeWord, it errors because its unfindable.

Upvotes: 2

Views: 2407

Answers (1)

Machinarius
Machinarius

Reputation: 3731

You might be better off implementing Knuth-Morris Pratt's algorithm, it might be faster than the internal .NET solution and it will allow you to know exactly where the strings are found. You can do substring concatenation magic afterwards, assign the result to the rtf's text and you'll be all set.

http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

Upvotes: 1

Related Questions