Count words in a text box

andrew104

Member
Joined
Nov 14, 2002
Messages
9
I have to count specific letters entered in a text box (which Ive completeed, as well as count the total number of words. I am going to call anything with a space before and after it a word. Im not really sure what to do for this. If someone has an idea it would be greatly appreciated! Thank you.

Here is my code to count a character...

Code:
     Count the number of times that character a is used in the string InputText
    Function strCountA1(ByVal InputText As String, ByVal a As Char) As Integer
        Dim i As Integer
        For i = 0 To InputText.Length - 1
            If InputText.Substring(i, 1) = a Then
                strCountA1 = strCountA1 + 1
            End If
        Next
    End Function
 
Code:
Dim sWords() As String = InputText.Text.Split(" "c)
MessageBox.Show(sWords.GetUpperBound(0).ToString(), Application.ProductName)
 
Thanks! How can I display the total in a label instead of a message box? Also, it seems to just count spaces, can I make it a little more selective and require some characters in between spaces? Thank you.
 
Ok regarding my first question about displaying it in a label, I figured it out.

Code:
        Me.WordCountLabel.Text = (sWords.GetUpperBound(0).ToString())

However, my question about making it more selective still stands. It is better than what I had before, but basically just counts spaces. Thanks.
 
Regular expressions are the easiest and best way if you want an accurate count of words in a String..

Code:
Dim r As New System.Text.RegularExpressions.Regex("\w+")
WordCountLabel.Text = r.Matches(InputText).Count

You can easily count how many times a is in a String as well...

Code:
Dim r As New System.Text.RegularExpressions.Regex("[a]{1}")
strCountA1 = r.Matches(InputText).Count
 
Last edited by a moderator:
Back
Top