关于vb.net里的substring的问题
VB.NET Code:
变量.Substring("ABCD田中一郎12345678EFGH",4,16)
想得到的结果是“田中一郎12345678”,但出来的结果是“田中一郎12345678EFGH”
请问VB.NET里用Substring截取字符串时把全角字符也看成是1位的吗?用过Mid方法也是出来同样的结果
请高手指点!
[解决办法]
Protected Function getByteSubstring(ByVal str As String, ByVal startIndex As Int32, ByVal ilong As Int32) As String
Dim strRetValue As String
Dim bytes As Byte()
Dim i As Integer
Dim istart As Integer
Dim count As Integer
count = ilong
strRetValue = ""
istart = startIndex
bytes = System.Text.Encoding.Unicode.GetBytes(str)
'bytes.GetLength(0)是字符串长度的2倍。
If startIndex < str.Length And ilong <= str.Length - startIndex Then
'将startIndex 转化为字节的起始位置
For i = 0 To startIndex * 2 - 1
'i是偶数是,bytes(i)存的值是当前字符的区码,为奇数位时,存的是位码。如果是字母(ASCII码字符),则位码的数值为0.否则不为0
If i Mod 2 = 1 Then
If bytes(i) > 0 Then '如果位码不为0,则是中文字符,字符的长度要加1
istart = istart - 1
End If
End If
Next
'将ilong 转为按字节要的字符串长度
For i = startIndex * 2 To ilong * 2 - 1
If i Mod 2 = 1 Then
If bytes(i) > 0 Then '如果位码不为0,则是中文字符,字符的长度要加1
count = count - 1
End If
End If
Next
strRetValue = str.Substring(istart, count)
End If
Return strRetValue
End Function