MTCoster
MTCoster

Reputation: 6145

Java - Split array at first instance of value

The method below receives byte[] b of indeterminate length. It contains a string of characters to be printed to a console-style window. I would like to split b at the first line-feed character, so that that character is included in the first array. However, at the moment this throws an ArrayOutOfBoundsError, because stringBytes and extraBytes are declared with zero size. How can I get around this problem?

byte[] stringBytes = {};
byte[] extraBytes = {};
int i = 0;

while(i < b.length) {
    stringBytes[i] = b[i];
    if(b[i] == '\n' && i + 1 != b.length) {
        while(i < b.length) {
            extraBytes[i - stringBytes.length] = b[i++];
        }

        break;
    }

    i++;
}

Upvotes: 1

Views: 154

Answers (3)

Joni
Joni

Reputation: 111249

You can use a ByteArrayOutputStream as a light-weight expandable array of bytes:

  • To add a byte use the write method.
  • To get the bytes that you have written so far, use the toByteArray method.

For example:

ByteArrayOutputStream stringBytes = new ByteArrayOutputStream();
ByteArrayOutputStream extraBytes = new ByteArrayOutputStream();
int i = 0;

while(i < b.length) {
    stringBytes.write(b[i]);
    if(b[i] == '\n' && i + 1 != b.length) {
        i++;
        extraBytes.write(b, i, stringBytes.length - i);
        break;
    }
    i++;
}

Upvotes: 0

Taylor
Taylor

Reputation: 4087

Try this:

byte[] stringBytes;
byte[] extraBytes;
int i = 0;

while(i < b.length) {
    if(b[i] == '\n' && i + 1 != b.length) {
        break;
    }

    i++;
}
stringBytes = java.util.Arrays.copyOf(b, i+1);
extraBytes = java.util.Arrays.copyOfRange(b, i+1, b.length - 1);

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

I would rather build a String out of the bytes and use the String APIs.

However, if you really need to do the byte operations that you can declare stringBytes and extraBytes as List<Byte> such as you can add as many values as needed without knowing their size.

Upvotes: 1

Related Questions