ヘッダー
C# サンプル集
 

文字列のバイト数を調べる

2022/7/31

→ Visual Basic のサンプルに切り替える → Python のサンプルに切り替える

 

"ABCあ" が Shift_JIS で 5バイトであることを確認する

#if NETCOREAPP
    //.NET Core で Shift_JIS を使用可能にします。
    System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
#endif

System.Text.Encoding SJIS = System.Text.Encoding.GetEncoding("shift_jis");
int byteCount = SJIS.GetByteCount("ABCあ");

System.Diagnostics.Debug.WriteLine(byteCount); //5

Debug.WriteLineが表示される場所

メモ:日本で 単に「文字列のバイト数」と言うとき、(伝統的な理由により)ほとんどの場合 Shift_JIS でのバイト数を指していると私は感じます。

 

 

"ABCあ" が UTF-8 で 6バイトであることを確認する

System.Text.Encoding UTF8 = System.Text.Encoding.UTF8;
int byteCount = UTF8.GetByteCount("ABCあ");

System.Diagnostics.Debug.WriteLine(byteCount); //6

 → Debug.WriteLineが表示される場所