UtterAccess HomeUtterAccess Wiki

Welcome Guest ( Log In | Register )

Custom Search
Edit Discussion
> GetStrOccurrences    

This function counts the number of occurrences of a substring within a string. Optionally will look for the "whole word" instead of any occurrance.

CODE

' Code courtesy of UtterAccess Wiki
' http://www.utteraccess.com/wiki/GetStrOccurrences
'
' You are free to use this code in any application,
' provided this notice is left unchanged.
'
' REV  DATE                          DESCRIPTION
' 1.0  2012-02-06                 initial release
' 2.0  2012-03-15                 added whole word option
Public Function GetStrOccurrences(ByVal strSearchFor As String _
                       , ByVal strSearchString As String _
                       , Optional intCompare = vbTextCompare _
                       , Optional blWholeWord As Boolean = False) As Long
'Searchs through the strSearchString for strSearchFor and returns the number
'of times that strSearchFor occurs.
   
   Dim aStrip() As Byte
   
   If Len(strSearchFor) = 0 Then Exit Function
   
   If blWholeWord = True Then
       
       'Strip the confusing characters
       aStrip = "~!@#$%^&*()_+=-{}`""'?/><.,[]|\" & vbCr & vbLf & vbTab  'Modify per your scenario.
       
       Dim i As Long
       
       For i = LBound(aStrip) To UBound(aStrip) Step 2
           strSearchString = Replace(strSearchString, Chr(aStrip(i)), " ", 1, , vbTextCompare)
       Next i
       
       'Pad the string being searched AS WELL AS the string being sought. Plus, dbl-space
       'the delimiter (string being sought) so the Split() works correctly.
       strSearchString = " " & Replace(strSearchString, " " & strSearchFor & " ", _
                                       "  " & strSearchFor & "  ", , , intCompare)
       strSearchFor = " " & strSearchFor & " "
       
   End If
       
   GetStrOccurrences = UBound(Split(strSearchString, _
                           strSearchFor, , _
                           intCompare))
       
End Function


Creative Commons License
GetStrOccurrences by UtterAccess Wiki is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Editing and revision of the content is freely encouraged; for details, see Expected Usage.

Edit Discussion
Custom Search
Thank you for your support!
This page has been accessed 3,422 times.  This page was last modified 14:54, 16 March 2012 by Brent Spaulding. Contributions by Jack Leach  Disclaimers