counting tokens in a string

Jason Rogers jacaetevha at fast-mail.org
Mon May 6 14:29:15 UTC 2002


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.  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 <= aString size) and: [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