|
-
Feb 5th, 2004, 10:48 PM
#1
Thread Starter
Fanatic Member
[VB] - Occurrences of a char in a string
V suprised I couldn't find a general purpose function that returns the number of times a character appears in a string...
so here's one i made
VB Code:
Public Function OccurrenceInstr(searchStr As String, char As String) As Integer
Dim lastSpot As Integer
Dim occCount As Integer
Dim found As Boolean
If searchStr = "" Or char = "" Then Exit Function
found = True
While found
lastSpot = InStr(lastSpot + 1, searchStr, char)
If lastSpot > 0 Then
occCount = occCount + 1
found = True
Else
found = False
End If
Wend
OccurrenceInstr = occCount
End Function
note: not thoroughly tested
Last edited by SkiNLaB; Feb 5th, 2004 at 11:26 PM.
-
Feb 6th, 2004, 07:49 AM
#2
VB Code:
Private Sub Command1_Click()
MsgBox CountChars("Hello there Lenny", "a")
End Sub
Private Function CountChars(ByVal SearchString As String, _
ByVal StrToFind As String, _
Optional ByVal IgnoreCase As Boolean = True) _
As Integer
If Len(SearchString) = 0 Or Len(StrToFind) = 0 Then Exit Function
If IgnoreCase Then
SearchString = LCase$(SearchString)
StrToFind = LCase$(StrToFind)
End If
CountChars = UBound(Split(SearchString, StrToFind))
End Function
Probably better not to do a lot of looping.
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
-
Feb 7th, 2004, 02:35 AM
#3
Thread Starter
Fanatic Member
-
Feb 7th, 2004, 05:30 PM
#4
Another way 
VB Code:
Option Explicit
Private Function CharCount(S As String, Char As String) As Integer
If Len(Char) = 0 Then Exit Function
Dim SR As String
SR = Replace(S, Char, vbNullString)
CharCount = (Len(S) - Len(SR)) / Len(Char)
End Function
Private Sub Form_Load()
MsgBox CharCount("manavo", "a")
End Sub
Last edited by manavo11; Feb 7th, 2004 at 05:48 PM.
Has someone helped you? Then you can Rate their helpful post. 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|