devxlogo

Counting characters in a file

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 #1text = Input$(LOF(1), 1)Close #1Dim charCount(255) As LongFor i = 1 To Len(text)    acode = Asc(Mid$(text, i, 1))    charCount(acode) = charCount(acode) + 1NextClose #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    NextEnd Sub

And here a few lines to test the routines:

Dim charCount(255) As LongCountFileCharacters "c:usasubscribers.txt", charCountMsgBox "the char 'A' was found " & charCount(Asc("A")) & " times"MsgBox "the char 'a' was found " & charCount(Asc("a")) & " times"

devx-admin

Share the Post: