一個變種更短,更優雅的方法@OOPer's solution將使用有條件綁定while
循環和index(_:offsetBy:limitedBy:)
爲了迭代8個字符的子字符串,利用當您嘗試提前超過限制時index(_:offsetBy:limitedBy:)
返回nil
這一事實。
let binaryBits = "010010000110010101111001"
var result = ""
var index = binaryBits.startIndex
while let next = binaryBits.index(index, offsetBy: 8, limitedBy: binaryBits.endIndex) {
let asciiCode = UInt8(binaryBits[index..<next], radix: 2)!
result.append(Character(UnicodeScalar(asciiCode)))
index = next
}
print(result) // Hey
請注意,我們通過Character
而不是在中間步驟String
去 - 這簡直就是拿那Character
is specially optimised的情況下UTF-8表示適合63個字節,這是事實的優點:這裏的情況。這節省了堆 - 爲每個字符分配一箇中間緩衝區。
純粹是爲了好玩,另一種方法可以是使用sequence(state:next:)
,以創建每個字符串的開始和結束的指標序列,然後reduce
,以所得的人物串連在一起成字符串:
let binaryBits = "010010000110010101111001"
// returns a lazily evaluated sequence of the start and end indices for each substring
// of 8 characters.
let indices = sequence(state: binaryBits.startIndex, next: {
index -> (index: String.Index, nextIndex: String.Index)? in
let previousIndex = index
// Advance the current index – if it didn't go past the limit, then return the
// current index along with the advanced index as a new element of the sequence.
return binaryBits.characters.formIndex(&index, offsetBy: 8, limitedBy: binaryBits.endIndex) ? (previousIndex, index) : nil
})
// iterate over the indices, concatenating the resultant characters together.
let result = indices.reduce("") {
$0 + String(UnicodeScalar(UInt8(binaryBits[$1.index..<$1.nextIndex], radix: 2)!))
}
print(result) // Hey
在它的面前,這似乎是要比第一個解決方案效率較低(由於這樣的事實,reduce
應該複製在每次迭代的字符串) - 但它出現的編譯器能夠執行一些優化,使其不會比第一個解決方案慢得多。
我認爲您的解決方案也很簡單。 – javimuu
那不是我的解決方案,我需要一個Ø獲得ascii值不是整數 – Appygix