Hi,
I have another string handling question for the group, since you have all
been so helpful in the past. Thank you.
Basically, I want to do something really simple:
Search a main string for a substring, then count how many times the
substring appears in the mainstring
e.g.
mainstring = "The man walked through the park, the man was
happy"
substring = "man"
Count = 2 (Because 'man' appears twice)
Now, to me this sounds like a very simple thing to do, (It is, right?) but I
have been working on it for 3 hours now and it's starting to make my brain
hurt.
The problem I am having (Take the main string I mentioned earlier, searching
for "Man") is moving the searcher to the right position. The second "man"
in my mainstring is at position 38. If the searcher gets to position 10 it
finds it at position 38 (so count = 2), if it moves to position 15, it finds
it at position 3 (count = 3), and as it continues until it gets past the
position it counts it every time it sees it.
I've tried coding so that every time a position is duplicated, count = count
+ 1 - 1. It works if the position occurs twice, but anymore than that
counts it! I think somehow I need to store the previous position count in a
variable, then check it with the current one and change the count number
accordingly. But i can't seem to get there!
I think my code is nearly there, it just needs a little something extra.
Can anyone help please?
Here is my code (I popped lots of msgboxes in there to try and help me see
where I was going wrong - to no avail!):
Dim mainstring As String 'Declare Variables
Dim searchstring As String
Dim searcher As Integer
Dim count As Integer
Dim Startpoint As Integer
mainstring = " " & txtMain.Text 'Initialise variables
searchstring = txtSearch.Text
Do
Startpoint = Startpoint + Len(searchstring) + 1
'Calculate place to start searching mainstring
MsgBox ("Startpoint = " & Startpoint)
searcher = InStr(Startpoint, mainstring, searchstring) 'Search
mainstring for searchstring, starting from calculated start
point.
MsgBox searcher
If (searcher > 0) Then 'If position of searchstring in
mainstring is > 0 then
count = count + 1 'add 1 to counter
MsgBox ("+ 1 to count")
ElseIf searcher = searcher Then 'If position or searchstring is
found twice, then
count = count + 1
count = count - 1 'Minus 1 from counter
MsgBox ("-1 from count")
End If
MsgBox ("Count = " & count)
'Display position of found word
Loop Until searcher = 0 'Loop until there are no more words
End Sub
Thanks!
Cassandra