Code archives/Algorithms/Sectors in string

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

Download source code

Sectors in string by Andres2005
IMO this is a very useful function. I'm using it myself and I will remain to use it too.

Here are some examples:
Sector("I don't play quitar!", " ", 0) ; returns "I"
Sector("I don't play quitar!", " ", 2) ; returns "play"
Sector("I don't play quitar!", " ", 3) ; returns "quitar!"
Function Sector$(txt$, separator$, sector%)
	Local result$ = "", occ
	For i = 1 To Len(txt$)
		If Mid$(txt$, i, 1) = separator$
			occ = occ + 1
		Else
			If occ = sector Then result$ = result$ + Mid$(txt$, i, 1)
		EndIf
		If occ > sector Then Exit
	Next
	Return result$
End Function

Comments

Jams2006
Thanks, i found this very useful when parsing argb colours formatted as "a#;r#;g#;b#" :)


Jams2006
And here's a handy function to go with it:

Counts the number of sectors within a string.

SectorCount( "1.0;1.0;1.0;1.0", ";" );returns 4
SectorCount( "test test", " " );returns 2
SectorCount( "Number of words in sentence", " " );returns 5
SectorCount( "testingtestingtesting", "ing" ) returns 3

Function SectorCount%( InString$, Seperator$ )
			Local Count% = 1

			For i% = 1 To Len( InString$ )
				If Mid( InString$, i%, Len( Seperator$ ) ) = Seperator$
					Count% = Count% +1
				EndIf
			Next
			Return Count%
End Function



Andres2006
SectorCount( "Number of words in sentence", " " );returns 5

Actually it returns 4 :P


Jams2006
It returns 5 for me....

But "testingtestingtesting" does return 4!
"testingtestingtest" would return 3.. small mistake :)


Andres2006
"Number of words in sentence" has only 4 spaces in it


Jams2006
Yeah but there's another word after the last space, it returns 5 for me as expected....


Jams2006
I believe in *proper* programmers speak this is called 'Tokenizing'???? I could be wrong, can anyone shed any light?


Code Archives Forum