Simple String Question.

Bijan Parsia bparsia at email.unc.edu
Wed May 15 15:53:39 UTC 2002


On Wed, 15 May 2002, Jimmie Houchin wrote:

> My books are at home and I am having difficulty finding how to put two 
> strings together.

As two others have pointed out #, is the concat operator (not just for
Strings, but for most collections).

Putting:
	'ab'.'bc'.'abbc'
in the top left pane of the method finder and hitting reture will find
this for you. (Yay method finder!!!)

> In Python and I think other languages (I believe) I can do in Smalltalk 
> form:
> 
> a := 'StringOne'
> b := 'StringTwo'
> c := a + b

Eww. Some people (me) sorta dislike overlading #+ that way :) (Yes, I use
Python :))

[snip]

Important tip: concat is usually more expensive in Squeak than, say, in
Python. Or rather, concat is not the preferred way to efficiently build
large strings. E.g.,

	'adfafds', 'adfdfa', 'adfa', 'adfasf'

will involve a fair bit of copying. A better way is to use a stream, and
here's one of my favorite idioms for it:

	String streamContents: [:strm | strm nextPutAll: 'adasfdaf';
					     nextPutAll: 'dafdak';...]

Disadvantage here is that you can still get a fair bit of copying, as the
stream starts with a small collection and then doubles it at appropriate
moments. To further tune you can do something like

	WriteStream on: (String new: 1000).

Which will preallocate in the stream a collection of (at least closer
to) the right size for a reasonably sized string.

Cheers,
Bijan Parsia.




More information about the Squeak-dev mailing list