String Function count() - Count all instances of a character in a string

Post your FreeBASIC source, examples, tips and tricks here. Please don’t post code without including an explanation.
Post Reply
dmontaine
Posts: 23
Joined: Mar 15, 2018 7:13

String Function count() - Count all instances of a character in a string

Post by dmontaine »

Slight modification of previously posted replace() function results in a new function count().

Useful if you need to find out how many delimited sub-strings are in a string. The number of sub-strings will be count()+1.

Code: Select all

'Program: CountFunctionExample
' This program demonstrates a count() function
' counts all instances of a character in a string

'==================================================
' count() function
'==================================================

function count(byval SearchString as string,byval SearchChar as string) as integer
	if len(SearchString) = 0 or len(SearchChar) = 0  then return 0
	
	dim CharCounter as integer
	dim sc as integer = asc(SearchChar)
	
	for Ctr as integer = 0 to len(SearchString) - 1
	    if SearchString[Ctr] = sc then CharCounter += 1      
	next
	
	Return CharCounter
end function

'==================================================
' Main Program
'==================================================
' Count the occurrences of "|"

width 80,24
dim InputString  as string = "a|b|c|d|e|f|g"

locate 1,1
print "count() function example program"
locate 3,5
print "The original string = " + InputString
locate 4,5
print "Intances of " + "|" + """ = " + str(count(InputString,"|"))
locate 6,1
print "Press any key to exit " ;
sleep

fxm
Moderator
Posts: 12081
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: String Function count() - Count all instances of a character in a string

Post by fxm »

We can also use 'INSTR' to do the job:

Code: Select all

function count(byval SearchString as string,byval SearchChar as string) as integer
    if len(SearchString) = 0 or len(SearchChar) = 0  then return 0
    dim CharCounter as integer = 0
    dim location as integer = 0
    do
        location = instr(location + 1,SearchString,SearchChar)
        if location = 0 then return CharCounter else CharCounter += 1
    loop
end function
Post Reply