準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にリストボックス (listBox1) を配置します。
サンプルコード (C#)
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! ";
listBox1.Items.Add("[" + s1 + "]");
string s2 = s1.Trim();
listBox1.Items.Add("[" + s2 + "]");
string s3 = s2.Trim('!');
listBox1.Items.Add("[" + s3 + "]");
}
}
}
解説
Trim メソッドを引数なしで使うと、文字列の前後のスペースを除去できます。引数に文字を指定すると、文字列の前後からその文字を除去します。
結果
動作確認環境
Visual Studio 2022 Professional (.NET 7 C#11)
ログ
初版:2016.04.20 Visual Studio 2015 Professional (C# 6.0)
