VB.NETで文字列をバイト単位で扱う場合、は関数を自作する必要があります。以下に関数の説明をします。
バイト単位で文字列を扱う場合は、Encodingクラスを使用します。
以下にバイト単で文字列を扱う、Left・Right・Mid・Len関数を記載します。
LeftB関数
文字列の左側より指定したバイト数文字を取得します。
Public Shared Function LeftB(ByVal str As String, ByVal byteCount As Integer) As String
Dim hEncode As System.Text.Encoding = System.Text.Encoding.GetEncoding("Shift_JIS")
Dim btBytes As Byte() = hEncode.GetBytes(str)
If byteCount <= btBytes.Length Then
Return hEncode.GetString(btBytes, 0, byteCount)
End If
Return str
End Function
RigthB関数
文字列の右側より指定したバイト数文字を取得します。
Public Shared Function RightB(ByVal str As String, ByVal byteCount As Integer) As String
Dim hEncode As System.Text.Encoding = System.Text.Encoding.GetEncoding("Shift_JIS")
Dim btBytes As Byte() = hEncode.GetBytes(str)
If byteCount <= btBytes.Length Then
Return hEncode.GetString(btBytes, btBytes.Length - byteCount, byteCount)
End If
Return str
End Function
MidB関数
文字列の指定位置より指定バイト数文字を取得します。
Public Shared Overloads Function MidB(ByVal str As String, ByVal startindex As Integer) As String
Dim hEncode As System.Text.Encoding = System.Text.Encoding.GetEncoding("Shift_JIS")
Dim btBytes As Byte() = hEncode.GetBytes(str)
If startindex <= btBytes.Length Then
Dim byteCount As Integer = btBytes.Length - startindex + 1
Return hEncode.GetString(btBytes, startindex - 1, byteCount)
End If
Return String.Empty
End Function
Public Shared Overloads Function MidB(ByVal str As String, ByVal startindex As Integer, ByVal byteCount As Integer) As String
Dim hEncode As System.Text.Encoding = System.Text.Encoding.GetEncoding("Shift_JIS")
Dim btBytes As Byte() = hEncode.GetBytes(str)
If startindex <= btBytes.Length Then
If (btBytes.Length - startindex) < byteCount Then
byteCount = btBytes.Length - startindex + 1
End If
Return hEncode.GetString(btBytes, startindex - 1, byteCount)
End If
Return String.Empty
End Function
LenB関数
文字列のバイト数を取得します。
Public Shared Function LenB(ByVal str As String) As Integer
Return System.Text.Encoding.GetEncoding("Shift_JIS").GetByteCount(str)
End Function
以上の関数では、最後に取り出す文字が、全角の場合半分に切れたるするので全角がある文字列では使えない。
全角半角の混じった文字列で使用するためには、以下の関数のように、文字を数えてじみちに取り出します。
・以下の関数は、最終文字が全角の前・後半分にかかった場合、指定バイト数より1バイト少ない文字列を戻しています。
LeftBC関数
Public Shared Function LeftBC(ByVal str As String, ByVal byteCount As Integer) As String
Dim hEncode As System.Text.Encoding = System.Text.Encoding.GetEncoding("Shift_JIS")
Dim n As Integer = 0
Dim m As Integer = 0
Dim l As Integer = str.Length
Dim i As Integer = 0
Do While (i < l)
n += hEncode.GetByteCount(str(i))
If byteCount < n Then Exit Do
m += 1
i += 1
Loop
Return Strings.Left(str, m)
End Function
RightBC関数
Public Shared Function RightBC(ByVal str As String, ByVal byteCount As Integer) As String
Dim hEncode As System.Text.Encoding = System.Text.Encoding.GetEncoding("Shift_JIS")
Dim n As Integer = 0
Dim m As Integer = 0
Dim i As Integer = str.Length - 1
Do While (0 <= i)
n += hEncode.GetByteCount(str(i))
If byteCount < n Then Exit Do
m += 1
i -= 1
Loop
Return Strings.Right(str, m)
End Function