Count occurrences of a character in a string

Post Reply
User avatar
rbytes
Posts: 1338
Joined: Sun May 31, 2015 12:11 am
My devices: iPhone 11 Pro Max
iPad Pro 11
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 »

I just count them
Attachments
IMG_9260.PNG
IMG_9260.PNG (82.46 KiB) Viewed 3128 times
Last edited by rbytes on Mon Feb 06, 2017 8:57 pm, edited 6 times in total.
The only thing that gets me down is gravity...

User avatar
Dav
Posts: 279
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 »

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: 1338
Joined: Sun May 31, 2015 12:11 am
My devices: iPhone 11 Pro Max
iPad Pro 11
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 »

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

Thanks, Dav. :idea:
The only thing that gets me down is gravity...

Joel
Posts: 57
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 »

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