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"

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may