2011-06-20 165 views
2

我想实现这样的事情:用字符串分割字节数组?

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

是否有可能使用String中的字节数组形式分裂?

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

回答

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(); 
} 
+0

这是我会怎么做 – Bohemian

+0

同意 - 我认为这是最可读的解决方案。 –