Parsing a string in SmallTalk

I am trying to switch each character in a line with one following (a-> b, y → z, etc.). Not sure though, how can I do this in Smalltalk and tried to combine this:

x := 'costam'. y := x asArray. y do: [:charr | charr := charr + 1. ]. y do: [:char | Transcript show: char printString; cr]. 

What I am doing is: iterate over the array and increment each character, although it does not work. I get an error: trying to save an argument. How do I get around this and do it properly?

Now I have something like this:

 x := 'costam'. y := x asArray. b := y at: 2. n := 1. m := 5. [ n < m ] whileTrue: [ n := n + 1. y at: n put: 'a'. Transcript show: (y printString). ]. 

The problem remains, how can I "increase" the characters, for example, → bg → h, etc.? Solvable

+4
source share
2 answers

Try the following:

 x := 'costam' answer := (x asIntegerArray collect: [ :c | c + 1]) asString. Transcript show: answer 
+1
source

From "Smalltalk-80":

Because argument names are pseudo-variable names, they can be used to access values, such as variable names, but their values ​​cannot be changed by purpose. In the spend:for: method spend:for: statement of the form

 amount =: amount * taxRate 

will be syntactically illegal since the value of the sum cannot be reassigned.

You can use the collect: message to create a new collection:

 z =: y collect: [:char | (ch asciiValue + 1) asCharacter ]. 

Character do not respond to + , so you will need to convert to Integer and vice versa. Note that since String are collections, they also respond to collect:

 x collect: [:ch | (ch asciiValue + 1) asCharacter ] 

If you only need ASCII characters, take the remainder modulo 128 before converting it back to a character.

 x collect: [:ch | (ch asciiValue + 1 \\ 128) asCharacter ] 

If you want to increase only letters, not other characters, add a conditional value to the block.

 x collect: [:ch | ch isLetter ifTrue: [(ch asciiValue + 1) asCharacter] ifFalse: [ch] ] 

Note that the last block does not process letters at the end of an adjacent range (for example, $z or, if the interpreter supports advanced ASCII or Unicode, $<16rD6> ), since the exact method depends on the capabilities of the system (basically, what is considered a letter).

+2
source

Source: https://habr.com/ru/post/1379921/


All Articles