I am using the following function to count occurrences of a given word or phrase in a larger string:[tt]
Function occurrences(ByVal searchString As String, ByVal fullString As String) As Integer
Dim upperSearchString As String = searchString.ToUpper()
Dim upperFullString As String = fullString.ToUpper()
Dim iStart As Integer = 0
Dim iCount As Integer = 0
Dim iStrLen As Integer = upperFullString.Length
Dim iPos As Integer
While iStart <= iStrLen
iPos = upperFullString.IndexOf(upperSearchString, iStart)
If (iPos > -1) Then
iCount = iCount + 1
iStart = iPos + upperSearchString.Length
Else
Exit While
End If
End While
Return iCount
End Function[/tt]
I want it to count words no matter where they appear in a sentence (first word, mid-sentence, or last word). And it is doing that well.
But it is also (currently) counting words within a word. For example, if I am searching for the word "if" - it will count "horrified" as an occurrence of the word "if"!
Is there some sort of modification that can be made to the above function to avoid it counting words like "if/horrified" in error? Would the use of a regular expression be appropriate here in addition to my function?
Thank you very much!
Lazer
Function occurrences(ByVal searchString As String, ByVal fullString As String) As Integer
Dim upperSearchString As String = searchString.ToUpper()
Dim upperFullString As String = fullString.ToUpper()
Dim iStart As Integer = 0
Dim iCount As Integer = 0
Dim iStrLen As Integer = upperFullString.Length
Dim iPos As Integer
While iStart <= iStrLen
iPos = upperFullString.IndexOf(upperSearchString, iStart)
If (iPos > -1) Then
iCount = iCount + 1
iStart = iPos + upperSearchString.Length
Else
Exit While
End If
End While
Return iCount
End Function[/tt]
I want it to count words no matter where they appear in a sentence (first word, mid-sentence, or last word). And it is doing that well.
But it is also (currently) counting words within a word. For example, if I am searching for the word "if" - it will count "horrified" as an occurrence of the word "if"!
Is there some sort of modification that can be made to the above function to avoid it counting words like "if/horrified" in error? Would the use of a regular expression be appropriate here in addition to my function?
Thank you very much!
Lazer