Vb6 Visual basic 6删除和添加字符串中的空格
我想在十六进制字符串中的每个字节后删除并插入空格 例如:如果十六进制字符串为Vb6 Visual basic 6删除和添加字符串中的空格,vb6,Vb6,我想在十六进制字符串中的每个字节后删除并插入空格 例如:如果十六进制字符串为 str = "0F0D3E" 然后我想在每个字节后插入空格,以获得 str = "0F 0D 3E" 反之亦然(从字符串中删除空格,使字符串再次变为“0F0D3E”)一种快速而天真的方法是: Option Explicit Private Sub Form_Load() Dim sSrc As String Dim sTgt As String sSrc = "0F0D3E"
str = "0F0D3E"
然后我想在每个字节后插入空格,以获得
str = "0F 0D 3E"
反之亦然(从字符串中删除空格,使字符串再次变为“0F0D3E”)一种快速而天真的方法是:
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
您可以利用
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
结果:
"0f030d"
"0f 03 0d "
"0f030d"
"0f 03 0d" trimmed
"0f030d"
"abc"
"a b c "
"abc"
"a b c" trimmed
"abc"
试试这个:
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
您尝试过什么?但是,应该避免在VB6中重复连接,因为它们非常昂贵。请参见Matthew Curland,高级Visual Basic 6,第14章.使用
Join()
和Replace()
也不是速度恶魔,尽管没有小字符串的大量串联那么糟糕。
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