You need to do a search on the text with a mark of all the words found. The problem is that the first word is marked, then if there is one more coincidence in the text, then the found word is not found but the next word.

if (textBox2.Text == "") MessageBox.Show("Введите текст"); else { string[] words = stroka.Split(new Char[] { ',', ' ', '\n' }); int index = stroka.IndexOf(textBox2.Text); for (int i = 0; i < words.Length; i++) { MessageBox.Show(words[i]); if (words[i] == textBox2.Text) { MessageBox.Show("Индекс входа " + index.ToString()); richTextBox1.SelectionStart = index; richTextBox1.SelectionLength = textBox2.TextLength; richTextBox1.SelectionColor = Color.Green; MessageBox.Show("Количество символов " + (richTextBox1.SelectionLength).ToString()); index = richTextBox1.SelectionLength + 1; } } } return stroka; 

I can not understand how to write, so that it takes the initial index not from the next word, but from the next match.

  • You would format the code to begin with as it should. - andreycha
  • What exactly to format? - arakul
  • Everything has already been done for you. - andreycha

1 answer 1

You can find the next entry in the string using the IndexOf() overload, which accepts the input index from which to start the search:

 index = richTextBox1.Text.IndexOf(textBox1.Text, index + textBox1.TextLength); 

Use this instruction instead of yours:

 index = richTextBox1.SelectionLength + 1; 

Result:

enter image description here

PS I proceeded from the assumption that stroka is richTextBox1.Text .