[Newbies] String construction and replacement

Claus Kick claus_kick at web.de
Mon Feb 2 19:40:44 UTC 2009


Claus Kick wrote:

>> 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)).
> ^str3

Woops, thats hardly generic ...

str := 'HI THERE BLA HI HERE'.
answer := (str (asArrayOfSubstringsSeparatedBy: (Character space))) 
asOrderedCollection.

pattern := 'HI'.
replacement := 'HELLO'.
resultString := ''.
i := 1.
answer do:[:element | (element = pattern ) ifTrue:[i = 1 
ifTrue:[resultString := resultString, replacement . i := i + i] 
ifFalse:[resultString := resultString, ' ', replacement ]] 
ifFalse:[resultString := resultString, ' ',  element]].
^resultString.




More information about the Beginners mailing list