[Newbies] String construction and replacement

Claus Kick claus_kick at web.de
Sun Feb 1 20:47:05 UTC 2009

Sebastian Nozzi wrote:

> Hello List,
> I've been struggling a bit with some basics about Strings for which I
> couldn't find an answer (yet).
> 1) How to construct a String from Characters?
> For example, I want to construct a String from the Chatacter literals:
> $H $I
> Character cr
> $T $H $E $R $E

Dirty solution:

|col str |
col := OrderedCollection new.
col add:$H
;add:  $I;
add: (Character cr);
add: $H;
add: $E;
add: $R;
add: $E.
str := String new.
col do: [:element | str := str, element asString].

This probably creates a bunch of unnecessary string objects, but I can 
never remember the best implementation.

> 2) How to replace a sequence of Characters in a String for others?
> For exaple, I want to replace every 'HI' (in this case only one) for
> 'HELLO' in the String above (not necesarily destructively, getting a
> new String is also ok). Is there a quick way to do that?

How about this?

| str3  str2 str index |

str := 'HI THERE'.
str2 := 'HI'.

index := str findString: 'HI'.
"str := str replaceFrom: index to: str2 size  with: 'HELLO' startingAt:1."

str3 := 'HELLO', (str copyFrom: (index + str2 size) to: (str size)).

More information about the Beginners mailing list