我想删除并在十六进制字符串中的每个字节后插入空格。
例如:如果十六进制字符串是
str = "0F0D3E"
然后我想在每个字节后插入空格来获取
str = "0F 0D 3E"
以及反向(从字符串中删除空格,使字符串变为" 0F0D3E"再次)。
答案 0 :(得分:0)
一种快速而天真的方法是:
Option Explicit
Private Sub Form_Load()
Dim sSrc As String
Dim sTgt As String
sSrc = "0F0D3E"
sTgt = SpaceIt(sSrc)
Debug.Print sTgt
sSrc = UnspaceIt(sTgt)
Debug.Print sSrc
End Sub
Private Function SpaceIt(sSrc As String) As String
Dim i As Long
Dim asSrc() As String
ReDim asSrc(0 To Len(sSrc) \ 2 - 1) As String
For i = 0 To Len(sSrc) - 1 Step 2
asSrc(i \ 2) = Mid$(sSrc, i + 1, 2)
Next i
SpaceIt = Join(asSrc, " ")
End Function
Private Function UnspaceIt(sSrc As String) As String
UnspaceIt = Replace(sSrc, " ", "")
End Function
答案 1 :(得分:0)
你可以利用Mid$
语句和Mid$
函数的强大功能和一点算术来编写一个函数,以便灵活高效地完成这项工作:
Private Function Spacify( _
ByVal Text As String, _
ByVal StrideIn As Long, _
ByVal StrideOut As Long, _
Optional ByVal RTrim As Boolean) As String
Dim OutLen As Long
Dim CopyLen As Long
Dim OutPos As Long
Dim InPos As Long
If StrideIn <= StrideOut Then
OutLen = (Len(Text) \ StrideIn) * StrideOut
If RTrim Then OutLen = OutLen - (StrideOut - StrideIn)
CopyLen = StrideIn
Else
OutLen = ((Len(Text) + (StrideIn - StrideOut)) \ StrideIn) * StrideOut
CopyLen = StrideOut
End If
Spacify = Space$(OutLen)
OutPos = 1
For InPos = 1 To Len(Text) Step StrideIn
Mid$(Spacify, OutPos) = Mid$(Text, InPos, CopyLen)
OutPos = OutPos + StrideOut
Next
End Function
示例:
Private Sub Main()
Dim S As String
S = "0f030d"
Debug.Print """"; S; """"
S = Spacify(S, 2, 3)
Debug.Print """"; S; """"
S = Spacify(S, 3, 2)
Debug.Print """"; S; """"
S = Spacify(S, 2, 3, True)
Debug.Print """"; S; """"; " trimmed"
S = Spacify(S, 3, 2)
Debug.Print """"; S; """"
Debug.Print
S = "abc"
Debug.Print """"; S; """"
S = Spacify(S, 1, 2)
Debug.Print """"; S; """"
S = Spacify(S, 2, 1)
Debug.Print """"; S; """"
S = Spacify(S, 1, 2, True)
Debug.Print """"; S; """"; " trimmed"
S = Spacify(S, 2, 1)
Debug.Print """"; S; """"
Stop
End Sub
结果:
"0f030d"
"0f 03 0d "
"0f030d"
"0f 03 0d" trimmed
"0f030d"
"abc"
"a b c "
"abc"
"a b c" trimmed
"abc"
答案 2 :(得分:0)
试试这个:
Private Sub Form_Load()
Dim str As String
Dim newstr As String
str = "0F0D3E"
newstr = AddSpaces(str)
str = Replace(newstr, " ", "")
End Sub
Private Function AddSpaces(s As String) As String
Dim i As Integer
For i = 1 To Len(s) Step 2
AddSpaces = AddSpaces & Mid$(s, i, 2) & " "
Next
AddSpaces = Trim(AddSpaces)
End Function