Code archives/Algorithms/Instr2

This code has been declared by its author to be Public Domain code.

Download source code

Instr2 by Chroma2006
Here's how this works. You have a string separated by commas:

str = "1,2,3,4876,325"

There are 4 commas in that string. This function will return the position of the commas specified. If you want to know the position of comma #3 then you would go:

c3 = Instr2( str, ",",3 )

It will return a 6. I wrote this so I could return large strings of information and then extract certain numbers from it.

If you wanted to extract the 4th value in your string, you would go:

index1 = Instr2(str,",",3)
index2 = Instr2(str,",",4)
return Mid(str,index1+1,index2-index1)

Simple!

This could also be useful for extracting information from multiplayer packets.

You could make a function like so:
Function Instr2:Int(str:String,sub:String,occ:Int)
	Local i:Int,f:Int,index:Int
	For i = 1 To occ
		f = Instr(str,sub,index)
		index = f + 1
	Next
	Return f
End Function


Function GetPacketValue(strPkt,strSep,intValue)
   Select intValue
      Case 1
         Return Mid( strPkt, 1, Instr2( strPkt, Chr(44), 1) - 1) )
      Case 2
         index1 = Instr2( strPkt, Chr(44), 1)
         index2 = Instr2( strPkt, Chr(44), 2)
         Return Mid( strPkt, index1+1, index2-index1)
      Case 3
         'blah blah
   End Select
End Function

Comments

None.

Code Archives Forum