思想
在用关键词遍历分割对象时,只存储位置和长度信息。遍历结束后,根据遍历时取到的信息进行截取。
源代码:
public static byte[][] split(byte[] in, byte[] keys) {
if ( in == null ) return null;
if ( keys == null || keys.length <= 0) return new byte[][] {in};
if (in.length < keys.length) return new byte[][] {in};
ArrayList<SplitedInfo> splited = new ArrayList<SplitedInfo>();
int pre_pos = 0;
int pos = 0;
int length = 0;
int len_in = in.length;
int len_keys = keys.length;
int max = (len_in - len_keys) + 1;
while(pos < max) {
// System.out.println("pos=" + pos + ",max=" + max);
if (compare(in, pos, keys) == true) {
// pos
// length
length = pos - pre_pos;
// System.out.println("★pos:" + pre_pos + ",length=" + length);
splited.add(new SplitedInfo(pre_pos, length));
pos += len_keys - 1;
pre_pos = pos + 1;
}
pos ++;
}
length = len_in - pre_pos;
if (length > 0) {
splited.add(new SplitedInfo(pre_pos, length));
}
// System.out.println("★pos:" + pre_pos + ",length=" + length);
byte[][] result = new byte[splited.size()][];
int i = 0;
for (SplitedInfo info : splited) {
if (info.getLength() == 0) {
result[i] = null;
} else {
result[i] = new byte[info.getLength()];
System.arraycopy(in, info.getPos(), result[i], 0, info.getLength());
}
i ++;
}
return result;
}
private static boolean compare(byte[] in, int pos, byte[] keys) {
int i = 0;
while(i < keys.length) {
if (keys[i] != in[pos + i]) {
return false;
}
i ++;
}
return true;
}
}
class SplitedInfo {
private int pos;
private int length;
public SplitedInfo() {
this.pos = -1;
this.length = -1;
}
public SplitedInfo(int pos, int length) {
this.pos = pos;
this.length = length;
}
/**
* @return pos
*/
public int getPos() {
return pos;
}
/**
* @param pos pos
*/
public void setPos(int pos) {
this.pos = pos;
}
/**
* @return length
*/
public int getLength() {
return length;
}
/**
* @param length length
*/
public void setLength(int length) {
this.length = length;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("pos=");
buf.append(this.pos);
buf.append(",length=");
buf.append(this.length);
return buf.toString();
}
}
测试程序:
import javay.util.UArys;
public class TestSplit {
public static void main(String[] args) {
byte[] a = new byte[10];
a[0] = 1;
a[1] = 1;
a[2] = 2; // 0, 2
a[3] = 1;
a[4] = 3;
a[5] = 2; // 3, 2
a[6] = 4;
a[7] = 2; // 6, 1
a[8] = 2; // 8, 0
a[9] = 5; // 9. 1
byte[] b = new byte[2];
b[0] = 2;
b[1] = 2;
byte[][] c = UArys.split(a, b);
System.out.println("test");
}
}
(结束)