Get number of occurrences of one string in another

Sumner, Walt WSUMNER at dom.wustl.edu
Thu Feb 23 14:48:36 EST 2012


Here's a small speed increment, still no repeat loops except for 3 or 4 hidden within Livecode. Counts "pppppp" as 3 "pp", not 5.

on mouseUp
   local timer1, timer2,pChunk, tCount1, tCount2
   put "asdfewoaevewppaafaeppaeafpntsrnpspsppsrhbsbppsbsargaregppsbrahargagbafpp" into pChunk
   put the ticks into timer1
   repeat 100000
     put substringCount1("pp",pChunk) into tCount1
   end repeat
  put the ticks - timer1 into timer1
   put the ticks into timer2
   repeat 100000
     put substringCount2("pp",pChunk) into tCount2
   end repeat
  put the ticks - timer2 into timer2
   put "dividing:" && timer1 & CR & "filtering:" && timer2 & CR & tCount1 &&  tCount2 && (tCount1=tCount2)
end mouseUp

function substringCount1 pString, pChunk
   local tLengthBefore
   put length(pChunk) into tLengthBefore
   replace pString with empty in pChunk
   return (tLengthBefore-length(pChunk)) div length(pString)
end substringCount1

function substringCount2 pString, pChunk
  replace pString with cr & pString & cr in pChunk
  filter pChunk with pString
  return the number of lines of pChunk
end substringCount2

OUTPUT
dividing: 35
filtering: 56
6 6 true

Walt


On Wed, Feb 22, 2012 at 8:47 PM, Bob Sneidar <bobs at twft.com> wrote:


Message: 22
Date: Wed, 22 Feb 2012 19:46:23 -0800
From: Bob Sneidar <bobs at twft.com>
To: How to use LiveCode <use-livecode at lists.runrev.com>
Subject: Re: Get number of occurrences of one string in another
Message-ID: <00EEDC47-B386-4BEC-9BCC-0E51671DC0A6 at twft.com>
Content-Type: text/plain; charset=us-ascii

only works for single characters.

function substringCount pString, pChunk
  replace pString with cr & pString & cr in pChunk
  filter pChunk with pString
  return the number of lines of pChunk
end substringCount

Bob

> On Feb 22, 2012, at 7:44 PM, Jerry Jensen wrote:
>
> > The offset() function has a third parameter: chars to skip. So if you
> call offset in a loop with the third param set to the previous result, and
> count loops until it returns 0, Bob's your uncle.
> >
> > On Feb 22, 2012, at 7:37 PM, Andrew Kluthe wrote:
> >
> >> function substringCount pChar, pString
> >>    put 0 into theCount
> >>    repeat for each char theChar in pString
> >>         if theChar is pChar then
> >>              add 1 to theCount
> >>         end if
> >>    end repeat
> >>    return theCount
> >> end substringCount
> >>
> >>
> >> Would work out nicely if there is not built in function for this.
> >>



More information about the use-livecode mailing list