counting characters in a text box

andrew104

Newcomer
Joined
Nov 14, 2002
Messages
9
Can somebody tell me how I would get started counting the total number of a certain letter in a text box as text is entered (realtime) ? Thanks.

P.S. What is the tag to display formatted code in here?
 
The tag is vb then /vb to end it. Include brackets like regular tags, of course.

The answer to your question should be as easy as this...

Visual Basic:
    Private Sub TextBox1_KeyPress(ByVal sender As Object, _
            ByVal e As System.Windows.Forms.KeyPressEventArgs) _
            Handles TextBox1.KeyPress

        Static counter As Integer   ' The counter!
        Dim c As Char = "a"c        ' The character to match.

        ' Match the lowercase version of the KeyChar to the character otherwise
        ' A and a are different. Note that you must return the KeyChar as a String
        ' before you can use ToLower.
        If e.KeyChar.ToString.ToLower = c Then
            counter += 1
            Console.WriteLine("Total = " + counter.ToString)
        End If
End Sub
 
Thank you for the help. :) I have figured out the single character,
however...

1. I'm now having trouble with counting the instances of "st".
I've tried an if statement (see code) and it counts correctly,
however if "s" is not the last character, then it displays "0" in the
label again. Any ideas?

2. Also, with the functions that I'm using, is there an easier way
to count lower and uppercase letters, rather than having
separate functions for each?

3. I need to count letters (A-Z). How can I keep a count of
those?

4. I also need to count words. Meaning a group of letters with a
space before and after them. Any ideas?


Thank you so much for your help! :) :D :) :D


Visual Basic:
' 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

    ' Count the number of times that character A is used in the string InputText
    Function strCountA2(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
                strCountA2 = strCountA2 + 1
            End If
        Next
    End Function

    ' Count the number of times that character e is used in the string InputText
    Function strCountE1(ByVal InputText As String, ByVal e As Char) As Integer
        Dim i As Integer
        For i = 0 To InputText.Length - 1
            If InputText.Substring(i, 1) = e Then
                strCountE1 = strCountE1 + 1
            End If
        Next
    End Function

    ' Count the number of times that character E is used in the string InputText
    Function strCountE2(ByVal InputText As String, ByVal e As Char) As Integer
        Dim i As Integer
        For i = 0 To InputText.Length - 1
            If InputText.Substring(i, 1) = e Then
                strCountE2 = strCountE2 + 1
            End If
        Next
    End Function

    ' Count the number of times that character s is used in the string InputText
    Function strCountS1(ByVal InputText As String, ByVal s As Char) As Integer
        Dim i As Integer
        For i = 0 To InputText.Length - 1
            If InputText.Substring(i, 1) = s Then
                strCountS1 = strCountS1 + 1
            End If
        Next
    End Function

    ' Count the number of times that character S is used in the string InputText
    Function strCountS2(ByVal InputText As String, ByVal s As Char) As Integer
        Dim i As Integer
        For i = 0 To InputText.Length - 1
            If InputText.Substring(i, 1) = s Then
                strCountS2 = strCountS2 + 1
            End If
        Next
    End Function

    ' Count the number of times that character v is used in the string InputText
    Function strCountV1(ByVal InputText As String, ByVal s As Char) As Integer
        Dim i As Integer
        For i = 0 To InputText.Length - 1
            If InputText.Substring(i, 1) = s Then
                strCountV1 = strCountV1 + 1
            End If
        Next
    End Function

    ' Count the number of times that character V is used in the string InputText
    Function strCountV2(ByVal InputText As String, ByVal s As Char) As Integer
        Dim i As Integer
        For i = 0 To InputText.Length - 1
            If InputText.Substring(i, 1) = s Then
                strCountV2 = strCountV2 + 1
            End If
        Next
    End Function

    ' Count the number of times that characters st are used in the string InputText
    Function CountSTTotal(ByVal InputText As String, ByVal t As Char) As Integer
        Dim i As Integer
        If InputText.EndsWith("s") Or InputText.EndsWith("S") Then
            For i = 0 To InputText.Length - 1
                If InputText.Substring(i, 1) = t Then
                    CountSTTotal = CountSTTotal + 1
                End If
            Next
        End If
    End Function

    'test countwords
    Function CountWords()
        Dim strWords() As String
        Dim lCounter As Long
        Dim lWordCount As Long
        strWords = Split(Trim(InputTextBox.Text), " ")
        For lCounter = 0 To UBound(strWords)
            If strWords(lCounter) <> " " And strWords(lCounter) <> "" Then lWordCount = lWordCount + 1
        Next lCounter
    End Function

    Private Sub InputTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles InputTextBox.TextChanged
        Collection1.Add(Me.InputTextBox)
        Me.ClearButton.Enabled = True
        Me.ACountLabel.Text = strCountA1(InputTextBox.Text, "a"c) + strCountA2(InputTextBox.Text, "A"c)
        Me.ECountLabel.Text = strCountE1(InputTextBox.Text, "e"c) + strCountE2(InputTextBox.Text, "E"c)
        Me.SCountLabel.Text = strCountS1(InputTextBox.Text, "s"c) + strCountS2(InputTextBox.Text, "S"c)
        Me.VCountLabel.Text = strCountV1(InputTextBox.Text, "v"c) + strCountV2(InputTextBox.Text, "V"c)
        Me.STCountLabel.Text = CountSTTotal(InputTextBox.Text, "t"c)
        Me.LetterCountLabel.Text = intLetterCount
    End Sub

    'test count letters
    Private Sub InputTextBox_KeyPress(ByVal KeyAscii As Integer)
        If (KeyAscii > 64 And KeyAscii < 91) Or (KeyAscii > 96 And KeyAscii < 123) Then
            'user typed a letter
            intLetterCount = intLetterCount + 1
            Me.LetterCountLabel.Text = intLetterCount
        End If
    End Sub
 
I'll try and point you in the right direction. If you are still having problems tomorrow I'll give you some more code. I'm not trying to mean or anything, it's just that I'm a strong believer in that you'll learn more when doing something yourself. :)

The answer to your questions are fairly simple, it's just that you need to know where to look! In .NET the object browser is your best friend and you should ALWAYS have it open at all times. If you have a question on how to do something most of the time I promise you the answer is within the object browser (assuming you know how object oriented programming works).

Okay, so. This object browser I speak of can be found at View -> Other Windows -> Object Browser (CTL+ALT+J).

Have a look around, get a feel for it. You'll also notice that it has a nifty search feature.

Now to point you in the right direction on where to find your answers...

1) Have a look at the mscorlib.System.String object (yes, String is an object!). Have a look at the IndexOf method. Think loop.

2) An array of some sort, but you'd need a flexible collection that accepts objects (so you can reference index a or A). Have a look at the mscorlib.System.Collections assembly. Perhaps ArrayList would do the trick or you could try Hashtable. If not have a look in the System.System.Specialized assembly and take a look at the Dictionaries provided there.

3) Isn't this the same as #2? :) Well, if you mean in a String then you can simply do a For Each loop using a Character object matching each String.ToCharArray then use some sort of array (see #2) to keep track of each character. Quick example:
Visual Basic:
Dim c As Char
Dim someString As String = "stuff"
For Each c In someString.ToCharArray
    yourArray(c) += 1
Next

4) See #1. Also do a search for Split and see what you can find. Quick example of possible solution;
Visual Basic:
Dim s As String
Dim someString as String = "stuff to split"
Dim count As Integer
For Each s In someString.Split(" "c)
    If s <> "" Then count += 1
Next
Please note that this split function returns an array with empty Strings of where it split at. A better solution can probably be found in regular expression splits so you can just return the arrays length rather then having to write a loop. Unfortunately I don't know regular expressions so I can't help you with that. :( Give me a few days though! :)

I hope this helps you in the long run. If you still need help after trying to find the answer yourself I'll offer up some more code for ya.
 
I'd suggest using a generic function which returns the number of times one string is present in another:

Visual Basic:
    Private Function InCount(ByVal strSource As String, ByVal strFind As String) As Integer
        Dim intStart As Integer = 0
        Dim intCounter As Integer = 0

        intStart = strSource.IndexOf(strFind, intStart)
        Do While intStart <> -1
            intCounter += 1
            intStart = strSource.IndexOf(strFind, intStart + strFind.Length)
        Loop

        Return intCounter
    End Function

With this example, InCount("ststst stst", "st") would return 5.

If you want to make it case-insensitive, you can just convert the source string to lowercase before passing it. A simple way of counting words would be to use InCount looking for a space, then add 1.
 
Well no reply either means a) we confused the heck out of you, b) you figured it all out or c) just haven't had a chance to get back to us. :) Either way, I finally got a chance to read up on Regular Expressions, which might I add, are insanely awsome. Doing everything you want is easily done using them.

To be honest I don't know of any places to learn about writing Regular Expression patterns (I'm reading about them in a book), but you can at least have a look at the assembly .NET provides; System.System.Text.RegularExpressions in the object browser.

Anyway, I wrote a console application that solves all 4 of your problems. At least I hope it does anyway to a certain extent. If you need further help let us know.

Visual Basic:
'To shorten code below that uses this assembly.
Imports System.Text.RegularExpressions

Module Module1
    Sub Main()
        'String to use.
        Dim str As String = "Split this and what not stst st st stst st."

        'Count instances of st.
        Console.WriteLine("Number of st's: " + _
            (Regex.Matches(str, "st").Count.ToString))

        'Individual characters. Can easily be turned into a function that passes
        'a character and returns an integer. Can use an ArrayList (or other)
        'to keep track of each character if need be.
        Dim c As Char = "a"c
        Console.WriteLine("Number of " + c + "'s: " + _
            (Regex.Matches(str, "[" + c + "]").Count.ToString))

        'Count all characters.
        Console.WriteLine("Numbers of all chars: " + _
            (Regex.Matches(str, "[A-Za-z]").Count.ToString))

        'Count words.
        Console.WriteLine("Number of words: " + _
            (Regex.Matches(str, "\w+").Count.ToString))

        Console.ReadLine()
    End Sub
End Module

Good luck and happy coding. :)
 
Couple questions...

1. Where are the values stored? I need to display them in a label.

2. Can I say say

Visual Basic:
    Dim str As String = InputTextBox.Text

I'll try it and see how it works. Thank you for all your help!
 
Back
Top