2013-07-24 63 views

回答

3

首先,您需要了解換行符只是相對於特定字符編碼的換行符。幸運的是,幾乎每個字符編碼都在底部使用相同的ASCII設置,\ n和\ r是其中的一部分。

有很多方法可以解決這個問題,不同程度的效率和複雜性。採取低效率但低複雜度的方法:

遍歷transformedToByteObject數組,如果字符不是(byte) '\r',則將其複製到目標數組。

如果它是'\r'那麼你也將它複製到你的目標數組,但檢查下一個字符是否爲'\n'。如果不是,則將其中一個插入到目標數組中。一些指針:你的目標數組最多隻能是你的輸入數組的2倍(最壞的情況,你的輸入數組只有滿了'\r')。因此,您可以使用transformedToByteObject.length * 2初始化您的目的地。保持寫入的字節的實際數目的一個計數器,一旦你知道的轉化長度,使用System.arrayCopy()

一種這樣的實現可能是這樣的那些字節拷貝到尺寸精確的另一個字節數組:

final byte[] original = ...; 
final byte[] transformed = new byte[original.length * 2]; 
int len = 0; 

for (int i = 0; i < original.length; i++) // for each original byte ... 
{ 
    transformed[len] = original[i];         // copy the byte 
    len++;                                  // track the number of transformed bytes written 

    if (original[i] == (byte) '\r')         // if this is a \r ... 
    { 
    if (i + 1 < original.length &&        // ... and there is a character that follows ... 
     original[i+1] != (byte) '\n')     // ... and that character is not a \n ... 
    { 
     transformed[len] = (byte) '\n';  // ... insert a \n 
     len++;        // ... being sure to track the number of bytes written 
    } 
    } 
} 

final byte[] result = new byte[len];              // prepare an exact sized array 
System.arrayCopy(transformed, 0, result, 0, len); // and copy the transformed bytes into it 
+0

糟糕 - 我的代碼有一個錯誤,如果最後一個字符是''\ r'',我們不會將其更改爲''\ r \ n''。我會把它作爲練習給讀者...... ;-) –