简体   繁体   English

字典到字符串

[英]Dictionary to string

I have dictionary "a Dictionary(#DOB->Date #Name->String #Salary->Number )" . 我有字典"a Dictionary(#DOB->Date #Name->String #Salary->Number )" I need to create a string which should be str:= "DOB Date,Name String,Salary Number" . 我需要创建一个字符串,它应该是str:= "DOB Date,Name String,Salary Number" I tried using keysAndValuesDo : but couldn't concatenate them correctly. 我尝试使用keysAndValuesDo :但无法正确连接它们。

You can do it in a nice way like this: 你可以用这样一个很好的方式做到这一点:

(dict associations collect: [ :assoc |
  assoc key asString, ' ', assoc value asString ])
    joinUsing: $,

if you want to use #do: and streams, you can go this way: 如果你想使用#do:和stream,你可以这样:

dict associations
  do: [ :assoc |
    aStream
      nextPutAll: assoc key asString;
      space;
      nextPutAll: assoc value asString ]
  separatedBy: [ aStream nextPut: $, ]

please note that in case you want to delegate printing to the object itself and not convert it to string and put in on the stream manually, you can use: 请注意,如果您想要将打印委托给对象本身而不是将其转换为字符串并手动放入流中,您可以使用:

aStream
  print: assoc key;
  ....

#print: method of a stream sends #printOn: to the parameter. #print:流的方法将#printOn:发送给参数。 #printOn: is the defat method you have to override to make your object properly printable on a stream. #printOn:是必须覆盖的#printOn:方法,以使您的对象在流上正确打印。 #asString uses #printOn: for a lot of objects. #asString使用#printOn:用于很多对象。

You can do it with keysAndValuesDo too. 你也可以用keysAndValuesDo来做。 Just remember that a Dictionary isn't ordered, and there is no nice keysAndValuesDo:separatedBy: 只记得一个字典没有被排序,并且没有很好的keysAndValuesDo:separatedBy:

|dict first str|
dict := OrderedIdentityDictionary 
    newFromPairs:#(#DOB Date #Name String #Salary Number).
first := true.
str := String streamContents: [  :s |
    dict keysAndValuesDo: [ :key :value |
        first ifFalse: [ s nextPutAll: ',' ]
            ifTrue: [ first := false].
        s   nextPutAll: key; space;
            nextPutAll: '';
            nextPutAll: value] ].
str

'DOB Date,Name String,Salary Number'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM