PDA

Click to See Complete Forum and Search --> : Counting no. of times one string appears within another


chrisjk
Nov 24th, 1999, 09:52 AM
Hi.

Subject says it all really. How can i write a function to count the number of times a string such as "moo" appears in another string, such as "cows go moo a lot. Do you moo? I can moo. Everybody must moo like I moo, or the moo monster will moo at you!" which in this case is 7.

Thanks for your assistance

Kind regards,

------------------
- Chris
chris.kilhams@btinternet.com

Aaron Young
Nov 24th, 1999, 10:46 AM
2 Methods:

Both Require 2 Textboxes and a Command Button..

1. Use the Replace Function in VB6..

Private Sub Command1_Click()
Dim iNum As Long
iNum = Len(Text1)
iNum = (iNum - Len(Replace(LCase(Text1), LCase(Text2), ""))) / Len(Text2)
MsgBox "The String: " & Chr(34) & Text2 & Chr(34) & " Appears in the Text " & iNum & " Times."
End Sub

2. Use the Instr Function..

Private Sub Command1_Click()
Dim iNum As Long
Dim iPos As Integer
Do
iPos = InStr(iPos + 1, LCase(Text1), LCase(Text2))
If iPos Then iNum = iNum + 1
Loop While iPos
MsgBox "The String: " & Chr(34) & Text2 & Chr(34) & " Appears in the Text " & iNum & " Times."
End Sub


------------------
Aaron Young
Analyst Programmer
aarony@redwingsoftware.com
adyoung@win.bright.net

chrisjk
Nov 24th, 1999, 11:07 AM
Thanks Aaron, this one was giving me jip

Kind regards,

------------------
- Chris
chris.kilhams@btinternet.com