What is a fast way to convert a string of two characters to an array of booleans?

前端 未结 8 1660
我寻月下人不归
我寻月下人不归 2021-02-04 10:24

I have a long string (sometimes over 1000 characters) that I want to convert to an array of boolean values. And it needs to do this many times, very quickly.

let         


        
8条回答
  •  轮回少年
    2021-02-04 11:11

    import Foundation
    
    let input:String = "010101011001010101001010101100101010100101010110010101010101011001010101001010101100101010100101010101011001010101001010101100101010100101010"
    var start  = clock()
    var output = Array(count: input.nulTerminatedUTF8.count, repeatedValue: false)
    var index = 0
    for val in input.nulTerminatedUTF8 {
        if val != 49 {
            output[index] = true
        }
        index+=1
    }
    var diff = clock() - start;
    var msec = diff * 1000 / UInt(CLOCKS_PER_SEC);
    print("Time taken \(Double(msec)/1000.0) seconds \(msec%1000) milliseconds");
    

    This should be really fast. Try it out. For 010101011010101001000100000011010101010101010101 it takes 0.039 secs.

提交回复
热议问题