# Smalltalk (Squeak) - String parsing

I'm learning Smalltalk programming as I think its way ahead as an OOP programming tool. I would appreciate feedback regarding my coding of the following problem. I have a sequence of letters representing bases in a DNA and want to change the T to a U in the string. I have done this in two ways. The first uses the copyReplaceAll:with: message to the string object which changes every occurrence of 'T' to a 'U':

string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
string copyReplaceAll: 'T' with: 'U'.


My second method uses iteration and boolean conditions to test whether a 'T' is identified. I learned that I have to copy the string to an Array object, then iterate over that object and copy the elements to an empty array. Ideally I would like the original string object to be mutable. Am I going at this the wrong way? Here's my code:

string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
strCopy := string asArray.
empty := Array new: strCopy size.
cntr := 1.

strCopy do: [:char |
(char = $T) ifTrue: [empty at:cntr put:$U ]
ifFalse: [empty at:cntr put: char].
cntr := cntr + 1
].

• This would have been a good question for the [smalltalk] and [pharo] tags of Stack Overflow. Next time consider asking there too. – Leandro Caniglia Jul 29 '17 at 12:07

Since Smalltalk is super interactive also try browsing through the methods of e.g. ByteString and other classes and the different ways to search for methods and their implementors:

You can actually run do: and at:put: on it directly, but there's also doWithIndex: for example, which looks like it will make your second bit even simpler:

string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
string doWithIndex: [ :char :i | (char = $T) ifTrue: [ string at: i put:$U ] ].


Now, in terms of readability, the first one is of course much easier to understand. It's to the point and obvious even for readers with no knowledge of Smalltalk. The second one and the example I posted aren't (or are less so at least) - they use more complex syntax and several new concepts.

If you restrict yourself to just String I think your second approach is fine though.

• Thank you Ferada for taking the time to help me with this. I can see that the doWithIndex: message makes the code neater without the need for a counter. – awyr_agored Jul 28 '17 at 23:25
• @awyr_agored Be aware that the expression string doWithIndex: [...] suggested by @ferada will modify your string, whereas your version left the original string unchanged and worked on a copy. – Leandro Caniglia Jul 29 '17 at 12:10