Normal Topic Counting Instances In A String (Read 750 times)
BWETTLAUFER
Full Member
***
Offline



Posts: 216
Location: Cambridge, Ontario
Joined: Apr 9th, 2010
Counting Instances In A String
Feb 5th, 2014 at 9:49pm
Print Post Print Post  
This is probably a silly question, but I'm not finding an explanation in the programming guide.

If I have a string value of "TL1 lmom -- TL2 na -- TPOE nis", and I want to count the instances of "TL" in the string (in this case, 2), what would be the way to go about that?

Thanks,
Blair
  
Back to top
IP Logged
 
The Cow
YaBB Administrator
*****
Offline



Posts: 2530
Joined: Nov 22nd, 2002
Re: Counting Instances In A String
Reply #1 - Feb 6th, 2014 at 2:04pm
Print Post Print Post  
Using a loop running from 1 to the length of the string, use @Mid to examine a portion of the string the same length as the test string (i.e.: "TL"). Using a conditional to test the result of the @Mid against the test string. If it matches, increment your counter.

It isn't very efficient, but it is straight-forward.
  

Mark Lasersohn&&Programmer&&Lantica Software, LLC
Back to top
IP Logged
 
BWETTLAUFER
Full Member
***
Offline



Posts: 216
Location: Cambridge, Ontario
Joined: Apr 9th, 2010
Re: Counting Instances In A String
Reply #2 - Feb 10th, 2014 at 3:17pm
Print Post Print Post  
Thanks Mark!  I'll try that with a 'IF @INSTR' to save time looping if nothing exists ...
  
Back to top
IP Logged
 
The Cow
YaBB Administrator
*****
Offline



Posts: 2530
Joined: Nov 22nd, 2002
Re: Counting Instances In A String
Reply #3 - Feb 10th, 2014 at 3:37pm
Print Post Print Post  
If you want to be more efficient, you can use just @instr on a variable holding a copy of the string, and trim that string to hold only the portion after the match - until no more matches are left. This is a bit more complicated, but also very efficient compared to running through a string in SBasic.

If speed is not an issue, it is probably better to write slower but more readable code.
  

Mark Lasersohn&&Programmer&&Lantica Software, LLC
Back to top
IP Logged
 
PianoMan
Member
Members
*
Offline


No personal text

Posts: 44
Joined: Oct 13th, 2004
Re: Counting Instances In A String
Reply #4 - Mar 12th, 2014 at 1:06pm
Print Post Print Post  
Here is a solution using @Instr(). It's pretty straight-forward and fast.
Code
Select All
var vString as String
var vFind as String
var vPos as Int
var vCnt as Int

vString = "AL-23... AD34--AL-678ALAL"
vFind = "AL"

If @Instr(vString, vFind) > 0
{
While @Instr(vString, vFind) > 0
{
  vPos = @Instr(vString, vFind)
  vString = @Mid(vString, vPos + @Len(vFind), @Len(vString))
  vCnt += 1
}
}

writeln(vCnt)

 

  
Back to top
IP Logged