2014-09-30 29 views
1

我有一個字節數組的數組。如何找到並用替換數據替換字節數組的一部分?如何做vb.net替換一個字節數組

暗淡foo的作爲字節 富= MY DATA

如果foo的是一個字符串,那麼我會做: 富=取代(FOO,目標,更換)

但是foo是一個字節數組。我該如何更換?

+2

「Byte」數組就像其他數組一樣。沒有找到一系列元素並將其替換的具體方法。你必須編寫你自己的代碼。找到合適的模式匹配算法並實現它。 – jmcilhinney 2014-09-30 05:37:20

回答

0

只爲它的樂趣,這裏是一個實現:

<TestMethod()> 
Public Sub Test_ArrayReplace() 
    AssertEqualArray({1, 4}, ArrayReplace({1, 2, 3}, {2, 3}, {4})) 
    AssertEqualArray({1, 4, 5}, ArrayReplace({1, 2, 3, 5}, {2, 3}, {4})) 
    AssertEqualArray({1, 4, 2}, ArrayReplace({1, 2, 3, 2}, {2, 3}, {4})) 
    AssertEqualArray({1, 4, 5, 2}, ArrayReplace({1, 2, 3, 2}, {2, 3}, {4, 5})) 
    AssertEqualArray({1, 2, 3, 8, 9}, ArrayReplace({1, 2, 3, 8, 2, 3, 4}, {2, 3, 4}, {9})) 

    AssertEqualArray({1, 68, 69, 70, 255}, ArrayReplace({1, 65, 66, 67, 255}, "ABC", "DEF", Encoding.ASCII)) 
End Sub 

Private Sub AssertEqualArray(expected() As Byte, actual() As Byte) 
    Assert.IsNotNull(expected, "expected") 
    Assert.IsNotNull(actual, "actual") 
    Assert.AreEqual(expected.Length, actual.Length, "length") 
    For index = 0 To actual.Length - 1 
     Assert.AreEqual(expected(index), actual(index), String.Format("index: {0}", index)) 
    Next 
End Sub 

Public Function ArrayReplace(data() As Byte, find As String, replacement As String, enc As Encoding) As Byte() 
    Return ArrayReplace(data, enc.GetBytes(find), enc.GetBytes(replacement)) 
End Function 

Public Function ArrayReplace(data() As Byte, find() As Byte, replacement() As Byte) As Byte() 
    Dim matchStart As Integer = -1 
    Dim matchLength As Integer = 0 

    Using mem = New IO.MemoryStream 
     For index = 0 To data.Length - 1 
      If data(index) = find(matchLength) Then 
       If matchLength = 0 Then matchStart = index 
       matchLength += 1 
       If matchLength = find.Length Then 
        mem.Write(replacement, 0, replacement.Length) 
        matchLength = 0 
       End If 
      Else 
       If matchLength > 0 Then 
        mem.Write(data, matchStart, matchLength) 
        matchLength = 0 
       End If 
       mem.WriteByte(data(index)) 
      End If 
     Next 

     If matchLength > 0 Then 
      mem.Write(data, data.Length - matchLength, matchLength) 
     End If 

     Dim retVal(mem.Length - 1) As Byte 
     mem.Position = 0 
     mem.Read(retVal, 0, retVal.Length) 
     Return retVal 
    End Using 
End Function 

的實現當然不是完美的,甚至可能是馬車。

請記住,爲了一個String轉換成你的ByteArray有知道StringEncoding。 您可以這樣稱呼它:

foo = ArrayReplace(foo, "find", "replace", Encoding.UTF8) 
相關問題