Problem

You have to justify text left, right and centre.

Solution

Dolphin Smalltalk has no built in methods to achieve this so you have to extend the string class with the new functionality. The following method shows how to justify text to the left by a given number.

leftJustify: aNumberOfChars

	"Answer a new string that is self + 
        a Number of spaces long, left justified"

	| aStringOfSpaces totChars |

	(aNumberOfChars <= self size) ifTrue: [^self].

	totChars := self size.
	totChars := (aNumberOfChars - totChars).

	aStringOfSpaces := String new.

	totChars timesRepeat: [aStringOfSpaces := 
           aStringOfSpaces , 
           (32 asCharacter asString)].

	^self , aStringOfSpaces.

To justify text to the right and to the centre is just a variation on the same theme.

Technorati tags: