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

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

Total Hit ( 3874)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


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
  Next

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
  Next
  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 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.