April 29, 2024, 05:22:01 AM

News:

IonicWind Snippit Manager 2.xx Released!  Install it on a memory stick and take it with you!  With or without IWBasic!


Finding occurences of a string

Started by Brian, May 07, 2011, 08:41:20 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Brian

Hi,

If I have a line of text, how do I count how many occurrences of a certain
character are in the line? Say it's a line of comma separated values, how
can I count how many commas are in the line?

Thanks,

Brian

Ficko


SUB FindString(InpStr:STRING,ToFind:STRING),INT
DEF Counter = 0:INT
DEF Pos:INT
Pos = INSTR(InpStr,ToFind)
WHILE (Pos)
Counter++
Pos = INSTR(InpStr,ToFind,++Pos)
ENDWHILE
RETURN Counter
ENDSUB

sapero

I would change it a bit, because when searching for "aa" in "aaa" Ficko's routine will find aa twice.
SUB FindString(InpStr:STRING,ToFind:STRING),INT
DEF Counter = 0:INT
DEF Pos:INT
int findlen = len(ToFind) ' added
Pos = INSTR(InpStr,ToFind)
WHILE (Pos)
Counter++
Pos = INSTR(InpStr,ToFind,/*changed*/Pos+findlen)
ENDWHILE
RETURN Counter
ENDSUB


And then, if you want to search for single characters, use this version (4 times faster)
SUB GetCharacterCount(InpStr:STRING,ToFind:char),INT
DEF Counter = 0:INT
DEF Pos=len(InpStr):INT
WHILE (--Pos>=0)
if (InpStr[Pos]==ToFind) then Counter++
ENDWHILE
RETURN Counter
ENDSUB

Brian

Thanks, guys. I ended up with this for a single character:

INT charCount=0
FOR loop=1 TO LEN(stringtocheck)
IF MID$(stringtocheck,loop,1)="," THEN charCount++
NEXT loop

But, of course, as usual, Sapero's code is usually the best!

Brian