Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java is there any good way to replace part of a byte[] with a byte[] of different length?

Tags:

java

I'm using airlift.joni, a new framework for regex. The main function of this framework is change string to byte[] and then do regex match and similar works. But since all elements are byte[], I can't use replace function in string and have to write my own replacement function.

I can get the start and end of the to-be-replaced pattern in a byte[] but don't know what's the proper way to replace it with a new byte[].

say we have a

byte[] A = new byte[10];

I want to replace A[2] to A[3] with a

byte[] B

whose length may not be 2. Is there some good way to do this? I only have the idea of creating a new array with length A.length+B.length-2 and copy every corresponding byte, but this will make the code too long.

like image 419
Eleanor Avatar asked Feb 09 '23 07:02

Eleanor


1 Answers

You have to allocate a new array for the result and then use System.arraycopy.

byte[] a = /*Allocated and initialized elsewhere*/;
byte[] b = /*Allocated and initialized elsewhere*/;
int replaceStart = 2; // inclusive
int replaceEnd = 4; // exclusive

byte[] c = new byte[a.length - (replaceEnd - replaceStart) + b.length];
System.arraycopy(a, 0, c, 0, replaceStart);
System.arraycopy(b, 0, c, replaceStart, b.length);
System.arraycopy(a, replaceEnd, c, replaceStart + b.length, a.length - replaceEnd);
like image 179
Andreas Avatar answered Feb 11 '23 21:02

Andreas