5
Contributors
12
Replies
15
Views
8 Years
Discussion Span
Last Post by Ramy Mahrous
0

I have one richtext box in my windows application and wrote few lines in that richtext box say - 7 lines
Now I want to read all the text of richtext box word by word and want to search particular word in those text.
I know there is find() in C# but I don't want to use that.

I hope now I am clear to every body

1

To get word by word then search on specific word

int GetWordIndex(string word)
{
char[] splitters = new char[]{' '};
string[] wordsArr = RichTextBox1.Text.Split(splitters, StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i< wordsArr.Length; i++)
if(string.Equals(wordsArr[i], word, StringComparison.InvariantCultureIgnoreCase))
return i;
return -1; //indicates there is no match
}
Votes + Comments
ramy got it again!
0

What do you want to use?

private void button1_Click(object sender, EventArgs e)
    {
      string find = "blu";
      if (0 <= richTextBox1.Text.IndexOf(find, StringComparison.InvariantCultureIgnoreCase))
      {
        System.Diagnostics.Debugger.Break();
        //found
      }
      else
      {
        // not found
      }
    }
0

To get word by word then search on specific word

int GetWordIndex(string word)
{
char[] splitters = new char[]{' '};
string[] wordsArr = RichTextBox1.Text.Split(splitters, StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i< wordsArr.Length; i++)
if(string.Equals(wordsArr[i], word, StringComparison.InvariantCultureIgnoreCase))
return i;
return -1; //indicates there is no match
}

You can also use RegEx's word boundary so you can handle splitting and removing punctuation:

private void button2_Click(object sender, EventArgs e)
    {
      string input = richTextBox1.Text;
      string[] words = System.Text.RegularExpressions.Regex.Split(input, @"\W+", System.Text.RegularExpressions.RegexOptions.Multiline);
    }
0

He can also add in splitters what you need
It may be also array of string to have something like that ("\r\n") if you read from text files.

0

Actually.. use the split option like Ramy suggested. My original post will match on a partial word :X

1

@Lighthead
You're welcome.
Nothing called stupid, you're trying to help and you should be thanked.
Nice to have you around and trying to help others.

Votes + Comments
Nice piece of code.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.