0

I have a byte array and want to split this with * char I am C++/Qt developer i can do this easy with this code in Qt

QByteArray byteArray;
QList<QByteArray> byteArrayList;

byteArray = file.readAll();
file.close();

byteArrayList = byteArray.split('*');

How can i split a byte array with char in C# ?

ARASHz4
  • 301
  • 1
  • 14

2 Answers2

1
byte[] bytes = File.ReadAllBytes("yourtextfile.txt");
string[] x = Encoding.UTF8.GetString(bytes).Split('*');

Change encoding if needed.

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
1

I'm not sure anything is inbuilt for that, since it isn't a common scenario; however you can search by index:

(all use of string here is purely for illustration; the actual split code doesn't use that)

static void Main()
{
    // pretend this isn't text
    byte[] bytes = Encoding.ASCII.GetBytes("askdjhkas*hdaskjdhakjshdjkahs*dkujyash");

    foreach(var chunk in Split(bytes, (byte)'*'))
    {
        // cheating with text to see if it worked
        var s = Encoding.ASCII.GetString(chunk.Array, chunk.Offset, chunk.Count);
        Console.WriteLine(s);
    }
}

static IEnumerable<ArraySegment<byte>> Split(byte[] data, byte splitBy)
{
    int start = 0, end;
    while((end = Array.IndexOf<byte>(data, splitBy, start)) > 0)
    {

        yield return new ArraySegment<byte>(data, start, end - start);
        start = end + 1;
    }
    end = data.Length;
    if ((end - start) > 0)
    {
        yield return new ArraySegment<byte>(data, start, end - start);
    }
}

Note: this would be a great scenario for "span" when that lands.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Can you please edit the question so it is clear what supposed to happen? (Is OP looking for equivalent of `string.Split` but for arrays?) – Alexei Levenkov Nov 21 '17 at 16:08
  • @AlexeiLevenkov I think so, yes – Marc Gravell Nov 21 '17 at 16:09
  • how to add this bytes to a list of bytes List bytesList = new List(); – ARASHz4 Nov 21 '17 at 16:48
  • @ARASHz4 I would strongly advise against that - that is going to force you to allocate more memory. Could you live with `List>>` ? if so: `var bytesList = Split(bytes, (byte)'*').ToList();`. As I say, "span" would be idea for this and would avoid extra allocs. If you *must* duplicate all the pieces, it can be done, sure – Marc Gravell Nov 21 '17 at 17:13
  • @marc-gravell how to convert List > to List – ARASHz4 Nov 21 '17 at 19:05