我有一个数据字节数组。如何使用替换数据查找和替换字节数组的一部分?
dim foo as byte foo =我的数据
如果foo是一个字符串,那么我会这样做: foo = replace(foo,target,replacement)
但是foo是一个字节数组。我怎样才能更换?
答案 0 :(得分: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,您 以了解Encoding
的{{1}}。
你可以这样称呼它:
String