Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a String instance from a sequence of integers?

I would like to create a test string from Unicode code points

Something like this

 65 asCharacter asString,
 66 asCharacter asString,
 67 asCharacter asString,
 65 asCharacter asString,
769 asCharacter asString

Or

String with: 65 asCharacter
       with: 66 asCharacter
       with: 67 asCharacter
       with: 65 asCharacter
       with: 769 asCharacter

This works but

I am looking for a way to convert an array of integer values to an instance of class String.

#(65 66 67 65 769)

Is there a built in method for this? I am looking for an answer like this What is the correct way to test Unicode support in a Smalltalk implementation? one, but for Strings.

like image 824
Kwaku Avatar asked Dec 08 '22 00:12

Kwaku


1 Answers

Many ways

1. #streamContents:

Use stream if you are doing larger string concatenation/building as it is faster. If just concatenating couple of strings use whatever is more readable.

String streamContents: [ :aStream |
    #(65 66 67 65 769) do: [ :each |
        aStream nextPut: each asCharacter
    ]
]

or

String streamContents: [ :aStream |
    aStream nextPutAll: (#(65 66 67 65 769) collect: #asCharacter)
]

2. #withAll:

String withAll: (#(65 66 67 65 769) collect: #asCharacter)

3. #collect:as: String

#(65 66 67 65 769) collect: #asCharacter as: String

4. #joinUsing: the characters

(#(65 66 67 65 769) collect: #asCharacter) joinUsing: ''

Note:

At least in Pharo you can use either [ :each | each selector ], or just simply #selector. I find the latter more readable for simple things, but that may be personal preference.

like image 180
Peter Uhnak Avatar answered Feb 02 '23 00:02

Peter Uhnak