2011-02-12 VB.NETで固定長文字列を生成する。
システム間インターフェイスで固定長ファイルを扱うケースがあると思いますが、
VB.NETやC#で固定長の文字列を作ろうとしても、そもそも.net framework には
標準で固定長文字列(ShiftJIS)を生成する機能が用意されていません。
全角(2バイト)文字を考慮すると、以下のような関数が必要となります。
''' -----------------------------------------------------------------------------------------
''' <summary>
''' 文字列を指定されたバイト数の固定長文字列に変換します。</summary>
''' <param name="Str">
''' 対象となる文字列。</param>
''' <param name="ByteCount">
''' バイト数(Shift-Jis)</param>
''' <returns>
''' 固定長文字列</returns>
''' -----------------------------------------------------------------------------------------
Public Shared Function GetSJisFixedString(ByVal Str As String, _
ByVal ByteCount As Integer)
Dim wkstr As String = Str.PadRight(ByteCount)
Dim hEncoding As System.Text.Encoding = _
System.Text.Encoding.GetEncoding("Shift_JIS")
Dim btBytes As Byte() = hEncoding.GetBytes(wkstr)
wkstr = hEncoding.GetString(btBytes, 0, ByteCount)
If hEncoding.GetByteCount(wkstr) > ByteCount Then
wkstr = hEncoding.GetString(btBytes, 0, ByteCount - 1) & Space(1)
End If
Return wkstr
End Function
コメントを書く