Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Collections and Blocks

Strings, Symbols and Streams in Smalltalk

Work with text in Smalltalk: String, Symbol and Character, concatenation, searching, splitting, formatting, and efficient building with ReadStream and WriteStream, including streams on collections.

Text in Smalltalk is just another collection: a String is an indexed sequence of Character objects, so everything you learned about arrays and iteration applies. On top come text-specific messages, the unique Symbol, and streams, the efficient way to read and write sequences piece by piece. This lesson covers all of them.

Smalltalk code is read-only on this site; the stand-ins run in JavaScript.

Strings

SMALLTALK
| s |
s := 'Smalltalk'.
s size.                    "-> 9"
s first.                   "-> $S"
s at: 3.                   "-> $a"
s asUppercase.             "-> 'SMALLTALK'"
s reversed.                "-> 'klatllamS'"
s , ' rocks'.              "-> 'Smalltalk rocks'"
s copyFrom: 1 to: 5.       "-> 'Small'"
s indexOf: $t.             "-> 6"
s occurrencesOf: $l.       "-> 3"
s includesSubstring: 'talk'.   "-> true"
s beginsWith: 'Small'.     "-> true"
s endsWith: 'talk'.        "-> true"
s asSymbol.                "-> #Smalltalk"
s asLowercase.             "-> 'smalltalk'"

Strings are collections: 'hello' select: [ :c | c isVowel ] answers 'eo'; 'hello' collect: [ :c | c asUppercase ] answers 'HELLO'; 'abc' do: [ :c | ... ] walks characters.

Mutation: strings are mutable (s at: 1 put: $X), but a literal string in a method is shared, so copy before changing: s copy at: 1 put: $X; yourself.

Splitting, joining, trimming

SMALLTALK
'a,b,c' substrings: ','.            "-> an OrderedCollection('a' 'b' 'c')"
'one two  three' substrings.        "-> splits on whitespace"
#('a' 'b' 'c') joinUsing: ', '.     "-> 'a, b, c'  (or: ', ' join: #('a' 'b' 'c'))"
'  padded  ' trimmed.               "-> 'padded'"
'hello world' replaceAll: $o with: $0.         "in place on a copy"
'hello world' copyReplaceAll: 'world' with: 'Pharo'.   "-> 'hello Pharo'"

Conversions

SMALLTALK
'42' asInteger.          "-> 42"
'42' asNumber.           "-> 42; works for '3.14' too"
'abc' asInteger.         "-> nil (not an error)"
42 printString.          "-> '42'"
42 asString.             "-> '42'"
255 printString: 16.     "-> 'FF'"
255 asStringWithCommas.  "grouping helpers vary by version"

Formatting

Pharo has a template format, with placeholders numbered from 1:

SMALLTALK
'Hello {1}, you are {2}' format: { 'Ada'. 36 }.     "-> 'Hello Ada, you are 36'"
'{1} + {2}' format: { 1. 2 }.

Use it instead of long chains of , and printString.

Characters

SMALLTALK
$a asInteger.        "-> 97"
97 asCharacter.      "-> $a"
$a isVowel.          "-> true"
$5 digitValue.       "-> 5"
$a < $b.             "-> true"
Character cr.  Character tab.  Character space.  Character lf.

Characters are unique objects. $a == $a is true.

Symbols

A Symbol is a String that is unique in the image: #hello == #hello is true, so symbol comparison is a pointer check. Symbols are immutable and print with #. They are used for selectors, keys and names.

SMALLTALK
#apple size.            "-> 5: symbols are strings"
#apple , 'seed'.        "-> 'appleseed' (a String)"
'apple' asSymbol == #apple.       "-> true"
#with:with: numArgs.    "-> 2"
3 perform: #factorial.            "-> 6: send a message chosen at run time"
3 perform: #+ with: 4.            "-> 7"

perform: is the dynamic message send, covered again in the reflection chapter.

Streams

Concatenating with , in a loop builds a new string every time, which is slow. A WriteStream collects pieces efficiently, and a ReadStream walks a sequence one element at a time.

WriteStream

SMALLTALK
| ws |
ws := WriteStream on: String new.
ws nextPutAll: 'Name: '; nextPutAll: 'Ada'; nextPut: $!; cr.
ws print: 42; tab; << 'done'.
ws contents.

A shortcut: String streamContents: [ :s | s << 'a' << 3 printString ]. The same works with arrays: Array streamContents: [ :s | 1 to: 3 do: [ :i | s nextPut: i * i ] ] answers #(1 4 9).

Stream messages for writing: nextPut:, nextPutAll:, print:, <<, cr, lf, tab, space, contents, reset.

ReadStream

SMALLTALK
| rs |
rs := ReadStream on: #(1 2 3 4 5).
rs next.                 "-> 1"
rs next: 2.              "-> #(2 3)"
rs peek.                 "-> 4: look without moving"
rs atEnd.                "-> false"
rs upToEnd.              "-> #(4 5)"
rs skip: -1.             "step back"

'hello world' readStream upTo: $ .       "-> 'hello'"

A typical parse loop:

SMALLTALK
| in tokens |
in := 'a b c' readStream.
tokens := OrderedCollection new.
[ in atEnd ] whileFalse: [ tokens add: (in upTo: $ ) ].
tokens.      "-> OrderedCollection('a' 'b' 'c')"

Files use the same protocol: file readStream and file writeStream (via FileSystem), so code that reads from a string can later read from a file unchanged.

Choosing

Task Tool
Join a few values , or format:
Build text in a loop String streamContents: / WriteStream
Tokenise or parse ReadStream with upTo:, peek, skip:
Compare names fast Symbol
JS Stand-in: strings as collections

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: ReadStream and WriteStream

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use a WriteStream to build a long string in a loop?

    Each , creates a new string. A WriteStream collects pieces and builds the result once.
  2. 2. What is special about a Symbol?

    Symbols are unique in the image, which makes comparison fast; they are used as selectors and keys.
  3. 3. What does 'abc' asInteger answer?

    asInteger answers nil for text that is not a number; check for nil before using it.
  4. 4. Which message answers the characters of a ReadStream up to a separator?

    upTo: reads until the separator (consumed) and answers what came before.

Summary

  • A String is a collection of Characters, so the whole collection protocol works; copy literals before mutating them.
  • Use , for quick joins, format: with placeholders for templates, substrings: to split.
  • A Symbol is a unique immutable string; use it for selectors and keys, and perform: to send a message by name.
  • WriteStream builds text or arrays efficiently; ReadStream parses with next, peek, upTo: and atEnd.
  • Files and strings share the stream protocol.

Next: Reflection and Introspection