Reese Houseknecht Reese Houseknecht - 20 days ago 4x Question

How to color multiple instances of a word in visual basc

when i use

RichTextBox1.SelectionStart = RichTextBox1.Find("println.")
RichTextBox1.SelectionColor = Color.Red

it only colors one of the words println. so i was wondering how i could color multiple instances of the word println. this was a thought.

Do Until 1 = 2
RichTextBox1.SelectionStart = RichTextBox1.Find("println.")
RichTextBox1.SelectionColor = Color.Red

but im not sure thats going to work


You can use a loop that will keep running as long as instances of the word are found, and at the end of each loop, set your start point for IndexOf to the end of the word you just highlighted. This way, the loop essentially moves through the string and ignores areas it has already searched in previous iterations. Here's an example of the concept:

    rtb1.Text = "one two three one two three one two three" 'text to search
    Dim search As String = "three" 'our search word

    Dim i As Integer = 0
    'while there is still another instance of our search word
    While i <> -1
        'get the first index starting after our previous index value
        i = rtb1.Text.IndexOf(search, i)
        If i <> -1 Then 'if we have one
            'then get the index of the end of the word so we can select it
            Dim iEnd As Integer = rtb1.Text.IndexOf(search, i) + search.Length
            rtb1.Select(i, search.Length) 'select the word
            rtb1.SelectionFont = New Font("Arial", 12, FontStyle.Bold) 'set its font
            'then, set our start point for the next loop iteration equal to the end of the word we just highlighted
            i = iEnd
        End If
    End While

The above changes the rtb's text from:

one two three one two three one two three


one two three one two three one two three