Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Counting characters in a file

Total Hit ( 3810)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


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:

Click here to copy the following block
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:

Click here to copy the following block
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

And here a few lines to test the routines:

Click here to copy the following block
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"


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.