|
|
Joined: Dec 1999
Posts: 30,867
Master Elite Member
|
Public Function String_CountChar(MyString As String, Char As String, CaseSens As Boolean) As Long
'Purpose
' Used to determine the number of times a specified character occurs in a string.
'Parameters
' MyString (String) = The string we're testing.
' Char (String) = The character we're counting.
' If this contains more than one character, only the first one is used.
' CaseSens (Boolean) = If True, the search is case-sensitive.
' If False, the search is not caps-sensitive.
'Return (Long)
' Returns the number of times the specified character occurs in MyString.
' Returns 0 (zero) if:
' MyString is zero-length.
' The specified character (Char) is zero-length.
' The specified character (Char) occurs zero times in MyString.
'Version History
' 1.0 3/27/2006 Tested by Russ Tanner on VB 6 Win 2000
'---
'Initiate variables
Dim TestChar As String 'the character we're counting
Dim i As Long 'index into MyString
Dim R As Long 'return buffer
'Default return value
String_CountChar = 0
'Trap: The specified character is zero-length, return default and exit now
If Len(Char) = 0 Then Exit Function
'The search is case-sensitive
If CaseSens Then
'Get the character we're counting
TestChar = Left(Char, 1)
'Loop through all characters in MyString
For i = 1 To Len(MyString)
'We found the character we're searching for, increment the counter
If Mid(MyString, i, 1) = TestChar Then R = R + 1
Next i
'The search is not case-sensitive
Else
'Get the character we're counting
TestChar = UCase(Left(Char, 1)) 'capitalize here to optimize speed
'Loop through all characters in MyString
For i = 1 To Len(MyString)
'We found the character we're searching for, increment the counter
If UCase(Mid(MyString, i, 1)) = TestChar Then R = R + 1
Next i
End If
'Return the result
String_CountChar = R
End Function
|
|
|
|
|