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).
- 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:$T; add: $H; add: $E; add: $R; add: $E. str := String new. col do: [:element | str := str, element asString]. ^str.
This probably creates a bunch of unnecessary string objects, but I can never remember the best implementation.
- 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)). ^str3