how to split an array into multiple sub-arrays that starts with specific value?

52 Views Asked by At

I am looking a way by C# to split an array into multiple sub-arrays that starts with specific value.

I have an array like this:

byte[] bytes = new byte[9];
bytes[0]=0x1a;
bytes[1]=0xAA;
bytes[2]=0xab;
bytes[3]=0xad;
bytes[4]=0xAA;
bytes[5]=0x01;
bytes[6]=0x02;
bytes[7]=0xAA;
bytes[8]= 0xac;

i want to split it into multiply arrays so that every new array start with 0xAA like below:

Array1: 0xAA, 0xab, 0xad

Array2: 0xAA, 0x01 0x02

Array3: 0xAA, 0xac

But i do not know how to implement.

Please help me some hints or codes. Thanks

1

There are 1 best solutions below

0
patvax On

You can iterate over the array with a for loop.

int? lastIndex = null;
byte[] subArray;
for(int index = 0; index < bytes.Length; index++)
{
    if(bytes[index] != 0xAA) continue;
    if(lastIndex is not null) 
    {
        int length = index - (int)lastIndex;
        subArray = new byte[length];
        Array.Copy(bytes, (int)lastIndex, subArray, 0, length);
        //Do something with subArray
    }
    lastIndex = index;
}
if(lastIndex is null) 
{
    // Handle the case when no 0xAA is found
    System.Console.WriteLine("No instances of 0xAA found");
    return;
}
subArray = new byte[bytes.Length - (int)lastIndex];
Array.Copy(bytes, (int)lastIndex, subArray, 0, bytes.Length - (int)lastIndex);
//Do something with last subArray

This finds occurences of 0xAA and creates the subarrays as copies. If you don't need a copy you may also create spans of the array regions like so:

int? lastIndex = null;
Span<byte> span;
for(int index = 0; index < bytes.Length; index++)
{
    if(bytes[index] != 0xAA) continue;
    if(lastIndex is not null) 
    {
        span = bytes.AsSpan((int)lastIndex, index - (int)lastIndex);
        //Do something with span
    }
    lastIndex = index;
}
if(lastIndex is null) 
{
    System.Console.WriteLine("No instances of 0xAA found");
    return;
}
span = bytes.AsSpan((int)lastIndex, bytes.Length - (int)lastIndex);
//Do something with last span

If you assign something to an element of span it will change your original array. If you don't want this you can use ReadOnlySpan<byte> in exactly the same way. But even then if you change the original array's values the span will reflect those changes.