2011-06-20 198 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

同意 - 我認爲這是最可讀的解決方案。 –