简体   繁体   中英

How to Convert Bit String to Boolean Array

In VB or C#, is there a concise way (no looping) to convert a string to a boolean array? I have a string of binary values representing days of the week ("0001100") and wish to convert to a boolean array (false, false, false, true, true, false, false).

No, there is no built in method for turning a string into a boolean array.

You have to do that by looping the characters in the string and check each one for the value, but you can easily do that with the Select method:

bool[] days = daysString.Select(c => c == '1').ToArray();

您可以使用LINQ来简单地转换:

"0001100".Select(c => c == '1').ToArray();

VB versions

Dim dayStr As String = "0001100"

Dim daysB() As Boolean
'using LINQ
daysB = dayStr.Select(Function(ch) ch = "1").ToArray

'using loop
Dim daysB1(dayStr.Length - 1) As Boolean

For idx As Integer = 0 To dayStr.Length - 1
    daysB1(idx) = dayStr(idx) = "1"
Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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