counting tokens in a string

gaelli at emergent.de gaelli at emergent.de
Mon May 6 15:06:53 UTC 2002


Jason Rogers <jacaetevha at fast-mail.org> schrieb am 06.05.2002, 16:29:15:
> I have the need to count tokens within a string, including 'empty'
> tokens.  Currently that capability doesn't exist (String implements
> counting tokens but _skips_ empty ones).
> 
> Being a (relative) Smalltalk newbie, I would like daggers thrown at the
> following code.  

OK, here they come... ;-)

Why don't you just count the number of delimters of each line and add 1?

('a,b;c,c,,' select: [:aChar| ',;' includes: aChar]) size + 1  ---> 6

(If you only had one kind of delimiter, you could even write something
like
('a,b,c,c,,' occurrencesOf: $,) + 1 ---> 6

Did I miss something?

Best,

Markus

My gut tells me that there must be a better way, but I
> don't quite know what that way is.
> 
> Thanks in advance,
> =jason
> 
> code snippet:
> "countTokens: aString
> 
> 	"Answers the number of tokens in this string, including 'empty' tokens.  A non-empty string with the absence of a delimeter returns a total of 1 (one) token."
> 
> 	| startIndex counter |
> 	(aString isEmpty) ifTrue:[^0].
> 	startIndex _ 1.
> 	counter _ 0.
> 	[(startIndex  0]]
> 		whileTrue: [
> 			startIndex _ aString findString: Delimeter startingAt: (startIndex + 1).
> 			counter _ counter + 1.
> 		].
> 	^ counter."
> -- 
>   Jason Rogers
>   jacaetevha at fast-mail.org



More information about the Squeak-dev mailing list