2

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).

BSalita
  • 8,420
  • 10
  • 51
  • 68

3 Answers3

7

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();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

You can use LINQ to simply convert:

"0001100".Select(c => c == '1').ToArray();
cuongle
  • 74,024
  • 28
  • 151
  • 206
0

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
dbasnett
  • 11,334
  • 2
  • 25
  • 33