简体   繁体   English

在java中有没有什么好方法用不同长度的byte []替换byte []的一部分?

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

I'm using airlift.joni, a new framework for regex. 我正在使用airlift.joni,一个新的正则表达式框架。 The main function of this framework is change string to byte[] and then do regex match and similar works. 这个框架的主要功能是将字符串更改为byte [],然后执行正则表达式匹配和类似的工作。 But since all elements are byte[], I can't use replace function in string and have to write my own replacement function. 但由于所有元素都是byte [],我不能在字符串中使用replace函数,必须编写自己的替换函数。

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[]. 我可以在byte []中获取待替换模式的开始和结束但不知道用新byte []替换它的正确方法是什么。

say we have a 说我们有一个

byte[] A = new byte[10];

I want to replace A[2] to A[3] with a 我想用A替换A [2]到A [3]

byte[] B

whose length may not be 2. Is there some good way to do this? 其长度可能不是2.有什么好方法可以做到这一点吗? 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. 我只想创建一个长度为A.length + B.length-2的新数组并复制每个相应的字节,但这会使代码太长。

You have to allocate a new array for the result and then use System.arraycopy . 您必须为结果分配一个新数组,然后使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM