IonicWind Software

IWBasic => General Questions => Topic started by: Brian on May 07, 2011, 08:41:20 AM

Title: Finding occurences of a string
Post by: Brian on May 07, 2011, 08:41:20 AM
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
Title: Re: Finding occurences of a string
Post by: Ficko on May 07, 2011, 10:52:33 AM

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
Title: Re: Finding occurences of a string
Post by: sapero on May 07, 2011, 11:58:16 AM
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
Title: Re: Finding occurences of a string
Post by: Brian on May 07, 2011, 04:16:35 PM
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