2014-02-23 131 views
1

我有一個字符串,看起來像:'1 3 4 5 7 8'如何在string中將字符串拆分爲單個字符?

我將如何迭代通過它將其分割成一個字符,以便每個字符我可以執行一個函數?

所以我的代碼如下所示:

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

我想每個setConcat數字的分離,同時另一方法添加的每個電話號碼之一。對不起,如果我不是很有幫助,我是Smalltalk的新手。

+0

看來它應該是'tempSet2Values:='4 5 6'' –

+0

抱歉。我的錯誤 –

回答

1

大多數Smalltalks支持String S上#findTokens:消息:

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

其中參數也可以是在字符串中的多個分隔符,像'.,;:'

根據方言,這可能是因爲#findTokens:採取StringCharacter

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

此外,你可能想在連接前做的分裂:

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

隨着單個輸入字符串的數量變大,這可以推廣。

+0

非常感謝! –

1

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 ] 
+0

謝謝你的迴應!那麼按空間分開呢?我試圖做一個阻止,但沒有奏效。 –

+0

我的Smalltalk的*小*生鏽,但在我看來,它應該改變'你好,你好,今天','你好。如何。你。今天'。也就是說,使用','作爲分隔符分割成子字符串,然後將這些部分放在一起,用'.'分隔。 –

+0

嗯...但如果我想我的字符串保持分離,我仍然會使用數組摺疊? –

0

一個明顯的可能性將是寫一個循環,通過字符串的字符步驟。

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

雖然還有不少可能性。

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

這將一次輸出一個字符串。使用抄錄窗口(菜單 - >工具 - >抄本)來測試。用您選擇的方法替換筆錄呼叫。

相關問題