devxlogo

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"

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Seven Service Boundary Mistakes That Create Technical Debt

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.