Count occurrences of a character in a string

Post Reply
User avatar
rbytes
Posts: 1963
Joined: Sun May 31, 2015 12:11 am
My devices: iPhone X
iPad 4
MacBook
Dell Inspiron laptop
CHUWI Plus 10 convertible Windows/Android tablet
Location: Calgary, Canada
Flag: Canada
Contact:

Count occurrences of a character in a string

Post by rbytes » Tue Jan 03, 2017 7:31 pm

I just count them
Attachments
IMG_9260.PNG
IMG_9260.PNG (82.46 KiB) Viewed 822 times
Last edited by rbytes on Mon Feb 06, 2017 8:57 pm, edited 6 times in total.
Zzzzz

User avatar
Dav
Posts: 302
Joined: Tue Dec 30, 2014 5:12 pm
My devices: iPad Mini, iPod Touch.
Location: North Carolina, USA
Contact:

Re: Count occurrences of a character in a string

Post by Dav » Tue Jan 03, 2017 9:31 pm

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

User avatar
rbytes
Posts: 1963
Joined: Sun May 31, 2015 12:11 am
My devices: iPhone X
iPad 4
MacBook
Dell Inspiron laptop
CHUWI Plus 10 convertible Windows/Android tablet
Location: Calgary, Canada
Flag: Canada
Contact:

Re: Count occurrences of a character in a string

Post by rbytes » Wed Jan 04, 2017 12:53 am

Good idea. I have altered the function as suggested and hope others will do the same.

Thanks, Dav. :idea:
Zzzzz

Joel
Posts: 58
Joined: Fri Jan 15, 2016 1:36 pm
My devices: miniipad
Flag: Germany

Re: Count occurrences of a character in a string

Post by Joel » Mon Jan 09, 2017 4:39 pm

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

Post Reply