如何在 do 块中连接字符串?

How to concatenate a string in a do block?

我正在尝试遍历一个数组并将该数组中的字符添加到另一个对象。问题是我一直收到错误 "Instances of character are not indexable"。但是,当我 运行 tag := tag,char 在 do 块之外时,它就起作用了。

|data startTag tag|.
data := '123456778'
startTag := false.
tag := ''.
data asArray do: [:char |
     tag := tag,char] 

,定义为

Collection>>, aCollection
^self copy addAll: aCollection; yourself

所以它会尝试对您的单个角色进行操作,就好像它是一个集合一样。这解释了错误。

对于较大的集合,您不希望使用 , 进行构建,因为每次都会发生复制。因此使用流协议:

|data tag|
data := '123456778'.
tag := String streamContents: [:s |
    data do: [ :char |
    s nextPut: char]]

另请参阅 Collection>>do:separatedBy: 以在数据之间添加分隔符。

[edit] 啊,好吧,就像

|data tag tags state|
data := '<html>bla 12 <h1/></html>'.
state := #outside.
tags := OrderedCollection new.
tag := ''.
data do: [ :char |
    state = #outside ifTrue: [
        char = $< ifTrue: [ 
            state := #inside.
            tag := '' ]]
    ifFalse:  [ 
         char = $> ifTrue: [ 
            state := #outside.
            tags add: tag] 
        ifFalse: [ tag := tag, (char asString)]]].
tags

"an OrderedCollection('html' 'h1/' '/html')"