I'm currently working on an exercise in squeak-Smalltalk. I want to split a string that behaves somewhat like split functions in Java or python, but hardly found anything on the internet. Any suggestions please? How can I implement it?
Thank you!
I'm currently working on an exercise in squeak-Smalltalk. I want to split a string that behaves somewhat like split functions in Java or python, but hardly found anything on the internet. Any suggestions please? How can I implement it?
Thank you!
I find the protocol browser most helpful for answering this question. Here are some selectors you could give a try:
'foo, bar, baz' splitBy: ','. "#('foo' ' bar' ' baz')"
'foo, bar, baz' splitBy: ', '. "#('foo' 'bar' 'baz')"
'foo, bar, baz' findTokens: ', '. "an OrderedCollection('foo' 'bar' 'baz')"
But note that while #splitBy:[Do:] interprets the parameter as a single separator sequence, #findTokens: uses it as a set of single char separators:
'foo bar, baz' splitBy: ', '. #('foo bar' ' baz')
'foo bar, baz' findTokens: ', '. an OrderedCollection('foo' 'bar' 'baz')
Hope this helps. Enjoy your Squeak!
SequenceableCollection >> splitBy: has existed in the Squeak image since at least February, 2010:
('1920x1080' splitBy: 'x') = #('1920' '1080')
Unfortunately no, it seems there is no split or splitBy: message in squeak (unlike Pharo...) so I implemented such a method by myself.
split: aSentence
|count str strArr |
str := aSentence.
count := ((aSentence select: [:a | a = $ ])) size.
strArr := OrderedCollection new.
[count >= 0]
whileTrue: [
strArr add: (str copyFrom: 1 to: (str indexOf: $ ifAbsent: [str size + 1]) - 1).
str := str copyFrom: ((str indexOf: $ ) + 1) to: (str size).
count := count - 1.
].
^strArr