Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4,VB5,VB6
Expertise: Intermediate
Sep 22, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Counting characters in a file

Ever needed to count how many characters of a given type are in a file? For instance, how many alphabetical characters, or digits, or spaces? You might read each line of the file using Line Input, but you will probably to load the whole file in memory using one single operation:

Open filename For Input As #1
text = Input$(LOF(1), 1)
Close #1
Dim charCount(255) As Long
For i = 1 To Len(text)
    acode = Asc(Mid$(text, i, 1))
    charCount(acode) = charCount(acode) + 1
Close #1
Here is a faster solution, up to four times faster, based on Byte arrays and encapsulated in a truly reusable procedure:

Sub CountFileCharacters(filename As String, charCount() As Long)
    Dim filenum As Integer
    Dim index As Long, acode As Integer

    On Error Resume Next
    filenum = FreeFile()
    Open filename For Binary As #filenum
    ' read the file contents in a temporary Byte array
    ReDim bArr(0 To LOF(filenum)) As Byte
    Get #filenum, , bArr()
    Close #filenum

    ' parse the array, update charCount()
    For index = 0 To UBound(bArr)
        acode = bArr(index)
        charCount(acode) = charCount(acode) + 1
End Sub
And here a few lines to test the routines:

Dim charCount(255) As Long
CountFileCharacters "c:\usasubscribers.txt", charCount
MsgBox "the char 'A' was found " & charCount(Asc("A")) & " times"
MsgBox "the char 'a' was found " & charCount(Asc("a")) & " times"
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date