Page 1 of 1

Count occurrences of a character in a string

Posted: Tue Jan 03, 2017 7:31 pm
by rbytes
I just count them

Re: Count occurrences of a character in a string

Posted: Tue Jan 03, 2017 9:31 pm
by Dav
Nice. That's the part of your Bulls and cows code that interested me the most.

The only thing I wonder is that perhaps we should not assume option base 1 in our functions when putting together a library for everyone? Maybe we should do the option_base$() call in the function, change option base at the beginning, reset it when leaving? just wondering about it, but I'm not a good one to say that because I always use option base 1 in my code, lol.

Great function by the way. Small code and very useful.

- Dav

Re: Count occurrences of a character in a string

Posted: Wed Jan 04, 2017 12:53 am
by rbytes
Good idea. I have altered the function as suggested and hope others will do the same.

Thanks, Dav. :idea:

Re: Count occurrences of a character in a string

Posted: Mon Jan 09, 2017 4:39 pm
by Joel
a general and more efficient solution:

Code: Select all

'option base 1
a$="Now is the time for all good men to come to the aid of their country"
i$="i"
PRINT "String: "&a$
PRINT "Character: "&i$
PRINT
chk=count_instr(a$,i$)
PRINT "Character '"&i$&"' appears "&chk&" times in string."


a$="Now is the time for all good men to come to the aid of their country"
i$="he"
PRINT "String: "&a$
PRINT "Character: "&i$
PRINT
chk=count_instr(a$,i$)
PRINT "Character '"&i$&"' appears "&chk&" times in string."

a$="xxxx"
i$="xx"
PRINT "String: "&a$
PRINT "Character: "&i$
PRINT
chk=count_instr(a$,i$)
PRINT "Character '"&i$&"' appears "&chk&" times in string."

print "option_base(): ";option_base()

DEF count_instr(string$,SUB$)
 result=INSTR(string$,SUB$)
 IF result=-1 THEN  RETURN 0
 IF result=LEN(string$)-LEN(SUB$)+OPTION_BASE() THEN RETURN 1 
 RETURN 1+ count_instr(MID$(string$,result+LEN(SUB$)),SUB$)
END DEF