? Count specific character in FIELD

  • Thread starter Thread starter JenniferM
  • Start date Start date
J

JenniferM

Guest
Need code to know how to count a specific character in a field, and how many times it occurs in the field.

Example
Field contains: The dog / went / to the store/ to get milk/

The "/" character shows up 4 times in the field. Need to be able to count this.

Different from the wildcard search that let me know it is IN the field.
 
You need to setup a progressive loop.

1. Store the field in a String
2. Use InStr to find the first occurance of "/" and increase a counter by 1 and store the position returned in, say intPos.
3. Truncate the string using something like myString=MID(myString,intPos+1)
4. Search new string again for "/", if found increase counter, else quit loop.

Hope this helps.
wink.gif
 
Function StrCount(TheStr As String, TheItem As Variant) As Integer
'------------------------------------------------------------------
' PURPOSE: Counts the numbers of times an item occurs
' in a string.
' ARGUMENTS: TheStr: The string to be searched.
' TheItem: The item to search for.
' RETURNS: The number of occurences as an integer.
'
' NOTES: To test: Type '? StrCount("The quick brown fox jumped over
' the lazy dog", "the") in the debug window.
' The function will return 2.
'------------------------------------------------------------------
Dim strhold As String, itemhold As Variant
Dim placehold As Integer
Dim i As Integer, j As Integer

strhold = TheStr
itemhold = TheItem
j = 0


If InStr(1, strhold, itemhold) > 0 Then
While InStr(1, strhold, itemhold) > 0
placehold = InStr(1, strhold, itemhold)
j = j + 1
strhold = Mid(strhold, placehold + Len(itemhold))
Wend
'Debug.Print "StrCount= " & j
End If
StrCount = j
End Function
 
Well if it was me I would...

'-----------------------------------------
Private Function CountChar(StringToSearch As String, CharToSearchFor As String)

Dim i As Integer
Dim intOccurances As Integer
Dim intCharLength As Integer

intCharLength = Len(CharToSearchFor)

For i = 1 To Len(StringToSearch)
If Mid(StringToSearch, i, intCharLength) = CharToSearchFor Then
intOccurances = intOccurances + 1
End If
Next

CountChar = intOccurances

End Function
'-----------------------------------------

...but that's just me.


[This message has been edited by cargobay 69 (edited 12-06-2001).]
 

Users who are viewing this thread

Back
Top Bottom