[Newbies] Find and replace
David T. Lewis
lewis at mail.msen.com
Sun Dec 30 15:43:30 UTC 2007
On Sun, Dec 30, 2007 at 01:23:49PM +0100, an organic wrote:
> Hello,
>
> i am new to smalltalk and i look for some easy way to find some substring in
> another string and replace it by another substring:
>
> example: string := 'Hello how are you? I am fine. Thank you and you?'
> substring to find 'you' replace by 'AA'
>
> transform to 'Hello how are AAA? I am fine. Thank AAA and AAA?'
You can search for suitable methods using the Method Finder
(world menu -> open... -> method finder). Try looking for methods
with names that contain 'replaceall' or names that contain
"copyreplace". In Smalltalk, it is common practice to copy strings
rather than modify characters within a string, so you will find
methods such as #copyReplaceAll:with:
Here is one way to do what you want:
'Hello how are you? I am fine. Thank you and you?'
copyReplaceAll: 'you'
with: 'AAA'
asTokens: false
If you know that the substrings that you want to replace are all
going to be "tokens" (surrounded by non-alphanumeric characters)
then you can use this to achieve the same result:
'Hello how are you? I am fine. Thank you and you?'
copyReplaceTokens: 'you'
with: 'AAA'
Note that in both cases, the method leaves the original string
intact and answers a new string with the substrings replaced, so
you might use it like this:
originalString := 'Hello how are you? I am fine. Thank you and you?'.
modifiedString := originalString
copyReplaceAll: 'you'
with: 'AAA'
asTokens: false.
Dave
More information about the Beginners
mailing list