用字符串拆分字节数组?

时间:2011-06-20 03:22:05

标签: java

我想实现这样的目标:

String sentence = "Hi there over there";
String[]result = sentence.split("there");
//you get result[0] = Hi, result[1] = over

是否可以使用字节数组格式的字符串进行拆分?

byte[]delimiter = "there".getBytes();
byte[]byteSentence = sentence.getBytes();
//then somehow split byteSentence using delimiter.

1 个答案:

答案 0 :(得分:5)

当然,您可以将字节数组转换为字符串:

byte[] delimiter = "test".getBytes();
byte[] sentence = "this is a test sentence".getBytes();

String[] result = new String(sentence).split(new String(delimiter));
byte[][] resultByte = new byte[result.length][];
for(int i = 0; i < result.length; i++){
    resultByte[i] = result[i].getBytes();
}