字串中文的問題,起於vb的字串是使用UniCode,而我們一般是使用Ascii Code。
這差別在何處呢?UniCode的每個字元長度是2個byte,而Ascii是一個byte,如果
說,我將們將VB的字串寫入檔案,有時會有意想不到的結果。例如:
Text1.Text = "這是一個abc"
len5 = Len(str5)
如果我們的Access資料庫有一欄位的長度是10個Byte,所以我們在TextBox中設定
MaxLength = 10,但是上面的例子得到的len5是7,而不是我們認為的11,因為不管
是中文或英文,vb一律以UniCode來存,所以str5的長度是7個"字元",而text1最大
的長度限制是10,7沒有超過10,故使用者仍可輸入,但存檔時,11個byte超過10個
byte,所以會有錯。
可是或許有人發現,使用RS232來傳資料時,另一端主機是Ascii編碼的機器,在vb中
我們若使用String來傳,一樣可以通啊,其實那是vb在傳送與接收data時,會做轉換
,使我們的程式設計較方便,但如果傳的資料是Binary時,就頭大啦。例如說,以字
串的方式來傳送資料,當想傳Ascii 大於128時,常有些問題,因為ASC(Chr(129))=0
,使我們不能用Chr()的指令來放資料。(事實上,您可以使用ChrW(129)來存資料,
和使用AscW()來取得值,加個W代表是Word的運算),這時候,就只有使用Byte Array
來做了。
1.UniCode轉成ByteAry
Dim byteAry() As Byte
Dim str5 As String
Dim i As Long
str5 = "這abc"
byteAry = str5
For i = LBound(byteAry) To UBound(byteAry)
Debug.Print byteAry(i) '得 25 144 97 0 98 0 99 0
Next i
Debug.Print Len(str5), LenB(str5) '得4 8
所以了,可看出UniCode 的特性,程式應改一下,使用Strconv()來轉換
Dim byteAry() As Byte
Dim str5 As String
Dim i As Long
str5 = "這abc"
byteAry = StrConv(str5, vbFromUnicode)
For i = LBound(byteAry) To UBound(byteAry)
Debug.Print byteAry(i) '得 25 144 97 98 99
Next i
Debug.Print LenB(StrConv(str5, vbFromUnicode)) '得5
2.ByteAry轉回UniCode 使用Strconv()轉換
Dim byteAry(10) as Byte
Dim Str5 as String
byteAry(0) = 25
byteAry(1) = 144
byteAry(2) = 97
byteAry(3) = 98
byteAry(4) = 99
Str5 = StrConv(byteAry, vbUniCode)
3.一些有用的函式
SubStr() 中文化取子字串,相對Mid()
Strlen() 中文化字串長度,相對Len()
StrLeft() 中文化取左字串,相對Left()
StrRight() 中文化取右字串,相對Right()
isChinese() Check某個字是否中文字
Public Function SubStr(ByVal tstr As String, start As Integer, Optional leng As Variant) As String
Dim tmpstr As String
If IsMissing(leng) Then
tmpstr = StrConv(MidB(StrConv(tstr, vbFromUnicode), start), vbUnicode)
Else
tmpstr = StrConv(MidB(StrConv(tstr, vbFromUnicode), start, leng), vbUnicode)
End If
SubStr = tmpstr
End Function
Public Function Strlen(ByVal tstr As String) As Integer
Strlen = LenB(StrConv(tstr, vbFromUnicode))
End Function
Public Function StrLeft(ByVal str5 As String, ByVal len5 As Long) As String
Dim tmpstr As String
tmpstr = StrConv(str5, vbFromUnicode)
tmpstr = LeftB(tmpstr, len5)
StrLeft = StrConv(tmpstr, vbUnicode)
End Function
Public Function StrRight(ByVal str5 As String, ByVal len5 As Long) As String
Dim tmpstr As String
tmpstr = StrConv(str5, vbFromUnicode)
tmpstr = RightB(tmpstr, len5)
StrLeft = StrConv(tmpstr, vbUnicode)
End Function
Public Function isChinese(ByVal asciiv As Integer) As Boolean
If Len(Hex$(asciiv)) > 2 Then
isChinese = True
Else
isChinese = False
End If
End Function
|
文章定位: