2012-05-28 35 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); 
}