String splitting

From Cuis CookBook
Jump to navigation Jump to search

Problem. You need to split a string into different parts. For example you may split a long text into lines or split the fields of a CSV line into records. You are probably looking around for something called split; it will not work, read on.

Solution. The easiest fix is to use send aString a findTokens: message. It is just an unusual name for something most of programming languages call split. The following example shows how to use findTokens: and its cousin findTokens:keep:.

'hello world' findTokens: ' '. " an OrderedCollection('hello' 'world') "

'hello world' findTokens: ' '. " an OrderedCollection('hello' 'world') " 

'foo,bar,baz' findTokens: ','. " an OrderedCollection('foo' 'bar' 'baz') " 

'foo,bar,baz' findTokens: ',' keep: ','. " an OrderedCollection('foo' ',' 'bar' ',' 'baz') "

'foo,bar,,baz' findTokens: ',' keep: ','. " an OrderedCollection('foo' ',' 'bar' ',' ',' 'baz') "

note. For months I have been using Cuis without knowing this fundamental method. I was using Regex to fill the gap, but it is like shooting a mosquito with a cannon. This stressed two points: 1) If you choose unusual names for your code poeple will not find/get you 2) Squeak Method Finder could be useful also in Cuis.


Dr. Nicola Mingotti wrote this page in 03-Dec-2021. Tested in Cuis5.0-4963.image.