C#にてstring(文字列)型の値がnullまたは空白でないかチェックするコードを紹介します。
文字列が有効な内容を含んでいるか、すなわち文字列が空か、あるいはnullかをチェックしたい場合があります。
文字列が有効な内容を含んでいるかをチェックする場合には IsNullOrWhiteSpace
メソッドを用いると簡単に判定できます。
String.Empty
メソッドやIsNullOrEmpty
メソッドを用いて判定することもできますが、IsNullOrWhiteSpace
メソッドを用いるとより低いコストで判定できます。private void button1_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
if (string.IsNullOrWhiteSpace(str) == true) {
textBox2.Text += "文字列は空白またはヌルです \r\n";
}
else {
textBox2.Text += "文字列は有効です \r\n";
}
}
//以前の方法
private void button2_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
if (string.IsNullOrEmpty(str) || str.Trim().Length==0) {
textBox2.Text += "文字列は空白またはヌルです \r\n";
}
else {
textBox2.Text += "文字列は有効です \r\n";
}
}
以下のUIを作成します。ButtonとTextBoxを1つづつ配置します。
以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NullAndWhiteSpaceCheck
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] data = new string[6];
data[0] = null;
data[1] = "Penguin";
data[2] = "";
data[3] = "あひる";
data[4] = " ";
data[5] = "\t\t \r\n";
for (int i = 0; i < data.Length; i++) {
string value = data[i];
if (string.IsNullOrWhiteSpace(value) == true) {
textBox1.Text += "nullまたは空白です。\r\n";
}
else {
textBox1.Text += string.Format("値は\"{0:s}\"です。\r\n", value);
}
}
}
}
}
data[0]~data[5]の文字列を順番に"IsNullOrWhiteSpace"で判定します。
プロジェクトを実行します。下図のウィンドウが表示されます。
[Button1]をクリックします。結果がテキストボックスに表示されます。