[All] Count occurrences in a string

Share your advanced PureBasic knowledge/code with the community.
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

[All] Count occurrences in a string

Post by BackupUser »

Code updated for 5.20+

Restored from previous forum. Originally posted by PB.

In one of my apps I just had need for this, so I thought I'd share...

Code: Select all

; Occurrences procedure by PB -- do what you want with it.
; Counts how many times a string exists in another string.
; Usage: r=Occurrences(source$,string$,case)
; Returns number of occurrences or 0 for none.
; Case must be 0 for off, or non-zero for on.
;
Procedure Occurrences(source$,string$,bCase)
  Repeat
    If bCase=0
      f=FindString(LCase(source$),LCase(string$),pos)
    Else
      f=FindString(source$,string$,pos)
    EndIf
    If f> 0 
      r=r+1 
      pos=f+Len(string$)
    EndIf
  Until f=0
  ProcedureReturn r
EndProcedure
;
Debug Occurrences("This is a thing","th",0) ; Case-sense off.
Debug Occurrences("This is a thing","th",1) ; Case-sense on.

PB - Registered PureBasic Coder