View this PageEdit this PageAttachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide
Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

Strings in Smalltalk by Jabari Worthy

Strings in Smalltalk by Jabari Worthy



Creating Strings
The first this to remember is that in Smalltalk strings are created with single quotes and not double quotes as you may be used to seeing in other language. In Smalltalk double quotes are for commenting. Here is an example of how to create a string in Smalltalk.

string := ‘I am a string’.



Printing to the console
The transcript show message is the common way to print things to the console in Smalltalk.

Transcript show: ‘Print me’.

The above line will print ‘Print me to the console’. To print a string variable you would do the same thing.

string := ‘Print me’.
Transcript show: string.

This code does the same thing as the first line of code.



Concatenating strings
In Smalltalk, a comma is used to concatenate strings.

String := ‘Part 1 ’, ‘Part 2 ’, ‘Part3’.

This line creates the string ‘Part1 Part2 Part3’ and stores it in the string variable.



Concatenating a string with line breaks
Just place a ‘\’ wherever you want a new line to begin, and return the string using the method withCRs. The withCRs message replaces the ‘\’ characters in your string with line breaks. There are other ways to place line breaks inside of strings but this is by far the easiest way that I’ve found.

string
string := ‘this is the first line\this is the second line’.
string := string, ‘\this is the third line.’.
^string withCRs.

An alternate version of the above code would be

string := ‘this is the first line’, ‘\this is the second line\this is the third line’ withCRs.

This creates the same string as the first code. These are just two different ways of concatenating them.



Return a substring
It is fairly simple to get a substring of a larger string in Smalltalk. All you have to do is use the copyFrom: to: message. For example

string := ‘xxxxHelloxxxx’.
substring := string copyFrom: 5 to: 9.

places the string ‘Hello’ into the substring variable. Also note that string indexes in Smalltalk start with 1 and not 0 as you may be familiar with seeing in other languages.



These are just some of the things you can do with strings in Smalltalk. For more examples you can visit the following webpages:

http://www.angelfire.com/tx4/cus/notes/smalltalk.html

http://www.cincomsmalltalk.com/blog/blogView?entry=3422855520


Link to this Page