準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にリストボックス (listBox1) を配置します
サンプルコード (C#)
using System.Text;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string s1 = "Hello, World" + "\0";
listBox1.Items.Add(BitConverter.ToString(Encoding.ASCII.GetBytes(s1)));
string s2 = s1.Trim('\0');
listBox1.Items.Add(BitConverter.ToString(Encoding.ASCII.GetBytes(s2)));
string s3 = s1.Replace("\0", "");
listBox1.Items.Add(BitConverter.ToString(Encoding.ASCII.GetBytes(s3)));
}
}
}
解説
null 文字は C#, C++/CLI では '\0' として扱い、V B.NET では Chr(0) として扱います。但し、文法上、文字列である必要がある時には、'\0' を "\0" として扱っています。Replace メソッドは '\0' は書けますが、空の文字リテラル '' を指定できないので、null 文字を文字列として扱っています。
結果
動作確認環境
Visual Studio 2022 Professional (.NET 7 C#11)
ログ
初版:2016.04.03 Visual Studio 2015 Professional (C# 6.0)
