Search code examples
vb.netcountword-count

Count words in Visual Basic


I am trying to implement a programme that counts the words in a multiline textbox as you type. I can get it counting the words until I press the "enter" key and type a word. It does not recognise this. This is my code:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles TextBox1.TextChanged
  Dim str As String
  Dim i, l, words As Integer
  str = TextBox1.Text

  str = LTrim(str) 'removes blank spaces at the beginning of text
  str = RTrim(str) ' removes blank spaces at the end of text
  l = str.Length
  i = 0
  words = 0
  While (i < l)
    If str(i) = " " Then
      words = words + 1
      i = i + 1
      While str(i) = " "  ' removes more than 1  blank space
        i = i + 1
      End While
    Else
      i = i + 1
    End If

  End While

  words = words + 1 ' adds the last word

  TextBox2.Text = ("" & words)

End Sub 

Solution

  • Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    
        Static rex As New System.Text.RegularExpressions.Regex("\b", System.Text.RegularExpressions.RegexOptions.Compiled Or System.Text.RegularExpressions.RegexOptions.Multiline)
    
        Label1.Text = (rex.Matches(TextBox1.Text).Count / 2).ToString()
    
    End Sub