advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Tip formerly from VB2TheMax
Expertise: Intermediate
Language: VB4,VB5,VB6
September 22, 2001
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
Next
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
Next
End Sub

It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com.
Already a member?





Francesco Balena
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
advertisement
advertisement