I have a string that looks like: '1 3 4 5 7 8'

How would I iterate through it to split it into a chars so that for each char I can perform a function?

so my code looks like this:

| tempSet1Values tempSet2Values setConcat |
tempSet1Values := '1 2 3'.
tempSet2Values := '4 5 6'.
setConcat := tempSet1Values , ' ' , tempSet2Values

I want to separate each of the numbers in setConcat and add each number one at a time to another method. Sorry if I am not as helpful, I am new to Smalltalk.

有帮助吗?

解决方案

Most Smalltalks support the #findTokens: message on Strings:

'1 2 3' findTokens: ' '. "-> anOrderedCollection('1', '2', '3')"

where the argument can also be multiple delimiters in the string, like '.,;:'.

Depending on dialect, it may be that #findTokens: does not take a String but a Character:

'1 2 3' findTokens: $ . "note the space" "-> anOrderedCollection('1', '2', '3')

Also, you probably do want to do the splitting before concatenation:

 | tempSetValues1 tempSetValues2 |
 tempSetValues1 := '1 2 3'.
 tempSetValues2 := '3 4 5'.
 (tempSetValues1 findTokens: ' '), (tempSetValues2 findTokens: ' ').

This can be generalized as the number of individual input strings gets larger.

其他提示

This rosetta code sample looks to do what you are looking for

|array |
array := 'Hello,How,Are,You,Today' subStrings: $,.
array fold: [:concatenation :string | concatenation, '.', string ]

One obvious possibility would be to write a loop that steps through the characters of the string.

|input |
1 to: input size do:
    [ :index |
        "here `input at: index` is the current character of the string"
    ]

There are quite a few more possibilities though.

'1 3 4 5 7 8'
inject: ''
into: [:str :each |
    (each sameAs: Character space)
        ifFalse: [
            Transcript show: each; cr ]].

This outputs a string one character at a time. Test this using a transcript window (Menu -> Tools -> Transcript). Replace the transcript call with the method of your choice.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top