How to transform a string of 0s and 1s into a boolean array

Single string

If you have a a string like "10101", you can use LINQ to convert it to a bit array.

string input = "10101";
bool[] flags = input.Select( c => c == '1' ).ToArray();

Array of strings

LINQ doesn't work so well with two-dimensional arrays, but it works fine with jagged arrays. If a bool[][] will do, this solution should work:

string[] input = { "10101","01010" };

bool[][] flags = input.Select
(
    s => s.Select
    ( 
        c => c == '1'
    )
    .ToArray()
)
.ToArray();

Here's a relatively ugly "one-liner":

string input = "1 0 1 0 1\n0 0 0 0 0\n1 0 0 0 1\n0 0 0 0 0\n1 0 1 0 1";
bool[][] flags = input.Split(new[] { "\n" }, StringSplitOptions.None) // Split into lines, e.g. [ "1 0 1 0 1", "0 0 0 0 0" ]
                      .Select(line => line.Split(' ') // Split each line into array of "1"s or "0"s
                                          .Select(num => num == "1").ToArray()) // Project each line into boolean array
                      .ToArray(); // Get array of arrays

But here is an (arguably more readable) version that probably comes closer to what I suspect is your actual use case, e.g. reading a line from the user one at a time.

string input = "1 0 1 0 1\n0 0 0 0 0\n1 0 0 0 1\n0 0 0 0 0\n1 0 1 0 1";

List<bool[]> boolArrays = new List<bool[]>();

string[] lines = input.Split(new[] { "\n" }, StringSplitOptions.None);
foreach (string line in lines) // Could be a different loop that gets lines from the user, e.g. `do { var s = Console.ReadLine(); doMore(); } while (s != null);`
{
    string[] charsAsStrings = line.Split(' '); // TODO: Improve variable names
    bool[] arrayRow = charsAsStrings.Select(numString => numString == "1").ToArray(); // Parsing to int would be pointless
    boolArrays.Add(arrayRow);
}

bool[][] flags = list.ToArray();

As noted in the comments, you typically want to use Environment.NewLine rather than "\n". Note that we can't split by a string without providing an entire array -- though that can be solved with extension methods.


Similar answer @Sinjai's. This works though by utilizing the fact that a string can be .Selected as a char[].

var boolVals = yourString.Replace(" ","").Replace("\r","")
    .Split('\n').Select(x => x.Select(y => y == '1').ToArray()).ToArray();

This works with a scenario where you might or might not have \r\n and spaces between every 1 or 0. If you had a string that looked like this:

string yourString = "10101\n10001";

then the code would be even shorter:

var boolVals = yourString.Split('\n').Select(x => x.Select(y => y == '1').ToArray()).ToArray();

Tags:

C#

Arrays