Get number of occurrences of one string in another

Peter M. Brigham, MD pmbrig at gmail.com
Thu Feb 23 09:06:48 EST 2012


Here's what I've been using for years, same idea, but more general:


function howmany tg,ctr
   if ctr = empty then return 0
   repeat for each item i in "8,7,6,5,4"
      put numtochar(i) into divChar
      if divChar is not in ctr then exit repeat
      if i = 4 then return "error in howmany()"
   end repeat
   replace tg with divChar in ctr
   set the itemdelimiter to divChar
   put the number of items of ctr into h
   if char -1 of ctr <> divChar then put h-1 into h
   return h
end howmany

This works for all strings. Note that there is an initial check to ensure that the replacement character is not contained in the string. The last if-then covers the anomaly that a trailing itemdelimiter is ignored in "the number of items of...".

-- Peter

Peter M. Brigham
pmbrig at gmail.com
http://home.comcast.net/~pmbrig


On Feb 22, 2012, at 10:47 PM, Bob Sneidar wrote:

> I am everyone's Uncle. Still, no repeat loops needed. See my solution.
> 
> 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.
>>> 
>>> --
>>> View this message in context: http://runtime-revolution.278305.n4.nabble.com/Get-number-of-occurrences-of-one-string-in-another-tp4412675p4412707.html
>>> Sent from the Revolution - User mailing list archive at Nabble.com.
>>> 
>>> _______________________________________________
>>> use-livecode mailing list
>>> use-livecode at lists.runrev.com
>>> Please visit this url to subscribe, unsubscribe and manage your subscription preferences:
>>> http://lists.runrev.com/mailman/listinfo/use-livecode
>> 
>> 
>> _______________________________________________
>> use-livecode mailing list
>> use-livecode at lists.runrev.com
>> Please visit this url to subscribe, unsubscribe and manage your subscription preferences:
>> http://lists.runrev.com/mailman/listinfo/use-livecode
> 
> 
> _______________________________________________
> use-livecode mailing list
> use-livecode at lists.runrev.com
> Please visit this url to subscribe, unsubscribe and manage your subscription preferences:
> http://lists.runrev.com/mailman/listinfo/use-livecode





More information about the use-livecode mailing list