最近,我遇到了一个看起来像这样的行:
Private Function FindCR(BinaryString)
FindCR = InstrB(1, BinaryString, Chr(13))
End Function
基本上,我给它一个二进制字符串,它应该给我一个回车索引。对于此示例,请使用ChrB(65) & ChrB(13) & ChrB(66) & ChrB(13) & ChrB(67) & ChrB(0)
,它相当于:
A
乙
C
但是,在这种情况下,FindCR
会在Chr(13)
= \13\0
后返回0并且我的字符串看起来像\65\13\66\13\67\0
。
我已尝试将Chr(13)
替换为ChrB(13)
(CR的二进制表示,而不是Char表示,因此\13
而不是{{1} }),但当Arg3的长度为0时,instrB返回\13\0
(在本例中为1)(当Arg1
为1时,lenB(ChrB(13))
为0。
有没有办法在二进制字符串中找到第一个回车符而不必操纵字符串和/或以len(ChrB(13))
的形式使用字符?
答案 0 :(得分:1)
在处理二进制字符串时,您可能仅通过检查回车来限制自己。根据我的经验,有人可以使用不同的文本编辑器来获得略有不同的字符串和/或您的源数据可能会发生变化(甚至从测试到生产)。行结束序列可以是vbCR或vbCR + vbLF或甚至其他组合。我建议你自己动手来获得你可能需要的灵活性:
Option Explicit
Private Function FindByteCode(binString() As Byte, _
Optional findChar As String = vbCr, _
Optional startChar As Long = 0) As Long
Dim i As Long
Dim start As Long
Dim eos As Long
If startChar > 0 Then
start = startChar
Else
start = LBound(binString)
End If
eos = 0
For i = start To UBound(binString)
If binString(i) = AscB(findChar) Then
eos = i
Exit For
End If
Next i
FindByteCode = eos
End Function
Sub test()
Dim testStr As String
testStr = "where is the end of the first vbCR " & Chr(13) & _
" and then the second?" & vbCr & vbLf
Debug.Print "first vbCR at " & FindByteCode(StrConv(testStr, vbFromUnicode))
Debug.Print "second vbCR at " & FindByteCode(StrConv(testStr, vbFromUnicode), startChar:=36)
Debug.Print "first vbLF at " & FindByteCode(StrConv(testStr, vbFromUnicode), findChar:=vbLf)
End Sub