I have a string (for example: "Hello there. My name is John. I work very hard. Hello there!"
) and I am trying to find the number of occurrences of the string "hello there"
. So far, this is the code I have:
Dim input as String = "Hello there. My name is John. I work very hard. Hello there!"
Dim phrase as String = "hello there"
Dim Occurrences As Integer = 0
If input.toLower.Contains(phrase) = True Then
Occurrences = input.Split(phrase).Length
'REM: Do stuff
End If
Unfortunately, what this line of code seems to do is split the string every time it sees the first letter of phrase
, in this case, h
. So instead of the result Occurrences = 2
that I would hope for, I actually get a much larger number. I know that counting the number of splits in a string is a horrible way to go about doing this, even if I did get the correct answer, so could someone please help me out and provide some assistance?
You can create a Do Until loop that stops once an integer variable equals the length of the string you're checking. If the phrase exists, increment your occurences and add the length of the phrase plus the position in which it is found to the cursor variable. If the phrase can not be found, you are done searching (no more results), so set it to the length of the target string. To not count the same occurance more than once, check only from the cursor to the length of the target string in the Loop (strCheckThisString).
You could create a recursive function using IndexOf. Passing the string to be searched and the string to locate, each recursion increments a Counter and sets the StartIndex to +1 the last found index, until the search string is no longer found. Function will require optional parameters Starting Position and Counter passed by reference:
Call function by passing string to search and string to locate and, optionally, start position:
Note the use of .ToLower, which is used to ignore case in your comparison. Do not include this directive if you do wish comparison to be case specific.
I don't know if this is more obvious? Starting from the beginning of
longString
check the next characters up to the number characters inphrase
, ifphrase
is not found start looking from the second character etc. If it is found start agin from the current position plus the number of characters inphrase
and increment the value ofoccurences
Looking at your original attempt, I have found that this should do the trick as "Split" creates an array. Occurrences = input.split(phrase).ubound
This is CaSe sensitive, so in your case the phrase should equal "Hello there", as there is no "hello there" in the input
Expanding on Sumit Kumar's simple solution (please upvote his answer rather than this one), here it is as a one-line working function:
Demo:
Yet another idea:
You just need to make sure that
phrase.Length > 0
.