Code archives/Miscellaneous/CountString function

This code has been declared by its author to be Public Domain code.

Download source code

CountString function by Zethrax2011
This function counts and returns how many times that one string (the 'needle' string) occurs inside another string (the 'haystack' string).

The function is case sensitive by default. Specify 'False' for the third parameter ('is_case_sensitive') to do a case insensitive check.
Function CountString( haystack$, needle$, is_case_sensitive = True )
	; This function counts how many times the 'needle$' string
	; occurs inside the 'haystack$' string.
	
	; Note that the function is case sensitive by default.
	; Specify 'False' for the 'is_case_sensitive' parameter;
	; for a case insensitive check.
	
	Local offset = 1, count
	
	If is_case_sensitive = False
		haystack$ = Lower$( haystack$ )
		needle$ = Lower$( needle$ )	
	EndIf
	
	Repeat
		offset = Instr ( haystack$, needle$, offset )
		
		If offset
			count = count + 1
			offset = offset + Len( needle$ )
		EndIf
		
	Until offset = 0
	
	Return count
End Function


; EXAMPLE USAGE


Print "Case Sensitive: " + CountString( "sABabcadadabAB", "AB" )
Print
Print "Not Case Sensitive: " + CountString( "sABabcadadabAB", "AB", False )

WaitKey : End

Comments

virtlands2012
Nice to see this interesting
CountString function by Zethrax

As an example;
s1$ = "1010101010101"
s2$ = "101"

find how many occurrences of s2 within s1:
There are two possible answers:
6 counts, { where you check at every single char offset. }
3 counts, { where you don't have overlaps = Zethrax's version }


Code Archives Forum