2012-05-28 73 views
0

我有這種方法在字節數組的開始處添加空格。問題是我不確定這是否是這個任務最快的實施。是否有一些選項可以更快地增加空間?如果是,請在這裏補充一些sollution如何給字節數組的開頭增加空格

public static byte[] doplnMezery(byte[] item, int numberOfSpaces) { 
    int lenghtOfItem = item.length; 

    for (int i = lenghtOfItem; i < numberOfSpaces; i++) { 
     item = ArrayUtils.add(item, 0, (byte) 32); 
    } 
    return item; 
} 
+0

通常的二進制數據被填充有'\ 0'代替空格。這個數組包含文本嗎?通常最快的做法是避免做這件事。你不能在你傳遞數組的地方添加空格嗎? –

+0

是的我知道0是平常的,但在要求是空間,所以我需要增加空間 – hudi

回答

4

這似乎是低效的,因爲add方法不能跑得比線性時間更快。你在這裏得到的是一個二次算法。

像這樣的東西應該更快(線性時間複雜度)。

public static byte[] doplnMezery(byte[] item, int numberOfSpaces) { 
    byte[] result = new byte[item.length + numberOfSpaces]; 
    Arrays.fill(result, 0, numberOfSpaces, (byte) 32); 
    System.arraycopy(item, 0, result, numberOfSpaces, item.length);   
    return result; 
} 
+0

thx很多Arrays.fill我在找什麼 – hudi

+0

啊。我懂了。別客氣。 – aioobe

1

嘗試這個代碼(JUnit測試) - 它添加 7空格items生產items2陣列:

@Test 
public void test1() throws Exception 
{ 
    byte[] items = new byte[] { 0x01, 0x02, 0x03 }; 
    byte[] items2 = new byte[3 + 7]; 

    System.arraycopy(items, 0, items2, 7, items.length); 
    Arrays.fill(items2, 0, 7, (byte)' '); 

    assertArrayEquals(new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0x02, 0x03 } , items2); 
}