Atlanta Custom Software Development 

   Search        Code/Page

User Login



Forgot the Password?
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
» Regular Expr Tester
» Free Tools

Count distinct characters in a string
[ All Languages » VB »  String]

Total Hit ( 3125)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article



When you need to count how many occurrences of a given character are in a string, you might be tempted to go along the "traditional" Visual Basic way:

Click here to copy the following block
' count spaces
  For i = 1 To Len(text)
    If Mid$(text, i, 1) = " " Then count = count + 1

Everything is easier if you use the capability to move a string into a Byte array. Here is a complete routine:
' count spaces

Click here to copy the following block
Function CountSpaces(ByVal sText As String) As Long
  Dim bArr() As Byte
  Dim i As Long
  Dim count As Long
  bArr() = sText
  For i = 0 To UBound(bArr) Step 2
    ' if this char is a space, increase the counter
    If bArr(i) = 32 Then count = count + 1
  CountSpaces = count
End Function

This approach can be up to three times faster than the traditional one.

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, SQL Server and other MS technologies. He is, 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.