如何在visual basc中为单词的多个实例着色

时间:2016-10-03 18:28:43

标签: vb.net

当我使用

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

它只会输出println中的一个字样。所以我想知道如何为println这个词的多个实例着色。这是一个想法。

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

但我不确定那会起作用

3 个答案:

答案 0 :(得分:1)

感谢您的帮助

  Dim search As String = "println." 'our search word
    Dim i As Integer = 0
    'while there is still another instance of our search word
    'println.
    While i <> -1
        'get the first index starting after our previous index value
        i = RichTextBox1.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 = RichTextBox1.Text.IndexOf(search, i) + search.Length
            RichTextBox1.Select(i, search.Length) 'select the word
            RichTextBox1.SelectionColor = Color.Red '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

这就是我所使用的,它对我正在做的事情非常有用,它为println这个词的所有实例着色。

答案 1 :(得分:0)

只要找到单词的实例,就可以使用一个会继续运行的循环,并且在每个循环结束时,将IndexOf的起点设置为刚刚突出显示的单词的结尾。这样,循环基本上在字符串中移动并忽略它在先前迭代中已经搜索过的区域。以下是这个概念的一个例子:

    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

以上内容改变了rtb的文字:

  一二三一二三一二三。

为:

  

一两一二一二

答案 2 :(得分:0)

要稍微扩展Nico的评论,有Find的重载允许您指定起始位置,因此您需要跟踪当前位置,记住跳过找到的文本,以便您重复找不到相同的事件:

Dim start = 0
Do
    start = RichTextBox1.Find(searchText, start, RichTextBoxFinds.None)
    If start >= 0 Then
        RichTextBox1.SelectionColor = Color.Red
        start += searchText.Length ' skip current occurrence
    End If
Loop While start >= 0 AndAlso start < RichTextBox1.Text.Length

注意:按照评论中的讨论进行了更新,但我并不完全确定我理解为什么RTB似乎会在传入等于文本长度的开头时重新启动搜索。

更新:查看RichTextBox.Find(String, Int32, RichTextBoxFinds)的{​​{3}}表示如果传入的start等于字符串的长度而end等于-1(默认值)对于此重载)然后将重置搜索范围以包括整个文本,从而重新开始搜索并导致@RawN发现无限循环。我不明白为什么它会这样,但它解释了需要额外的AndAlso start < RichTextBox1.Text.Length检查。