このエントリーをはてなブックマークに追加


スペースのみの文字列、空の文字列、サイズ0の文字列を判定する

半角スペースのみの文字列、null(Nothing)な文字列、サイズ0の文字列を判定する C#, Visual Basic のサンプルコードを紹介します。
Stringクラスには半角スペースのみ、空の文字列、サイズ0の文字列を判定するのに、
String.IsNullOrEmpty, String.IsNullOrWhiteSpace という便利なメソッドがあります。

関連サイト

動作確認環境

  • Windows 10
  • Visual Studio 2019
  • .NET Core 3.1
  • コンソールアプリケーション

C#, Visual Basic サンプルコードと実行結果

以下にString.IsNullOrEmpty, String.IsNullOrWhiteSpaceのサンプルコード紹介と実行結果を記します。
文字列が条件に成立すれば、true, 不成立であれば false が返却されます。
実際のプログラミングでは、ifにより判定することになりますね。

C#

using System;

class Program
{
    static void Main(string[] args)
    {
        string empty = "";
        string nothing = null;
        string white_space = @"   ";

        Console.WriteLine("-- String.IsNullOrEmpty --");
        Console.WriteLine("empty: " + String.IsNullOrEmpty(empty));
        Console.WriteLine("nothing: " + String.IsNullOrEmpty(nothing));
        Console.WriteLine("white_space: " + String.IsNullOrEmpty(white_space));

        Console.WriteLine("-- String.IsNullOrWhiteSpace --");
        Console.WriteLine("empty: " + String.IsNullOrWhiteSpace(empty));
        Console.WriteLine("nothing: " + String.IsNullOrWhiteSpace(nothing));
        Console.WriteLine("white_space: " + String.IsNullOrWhiteSpace(white_space));
    }
}

Visual Basic

Imports System

Module Program
    Sub Main(args As String())
        Dim empty As String = ""
        Dim null As String = Nothing
        Dim white_space As String = "   "

        Console.WriteLine("-- String.IsNullOrEmpty --")
        Console.WriteLine("empty: " & String.IsNullOrEmpty(empty))
        Console.WriteLine("nothing: " & String.IsNullOrEmpty(Nothing))
        Console.WriteLine("white_space: " & String.IsNullOrEmpty(white_space))

        Console.WriteLine("-- String.IsNullOrWhiteSpace --")
        Console.WriteLine("empty: " & String.IsNullOrWhiteSpace(empty))
        Console.WriteLine("nothing: " & String.IsNullOrWhiteSpace(Nothing))
        Console.WriteLine("white_space: " & String.IsNullOrWhiteSpace(white_space))
    End Sub
End Module

実行結果

上記のサンプルコードを実行したときのキャプチャになります。

01.png

以上、String.IsNullOrEmpty, String.IsNullOrWhiteSpaceを使って、
空の文字列、サイズが0の文字列、半角スペースのみの文字列を判定するサンプルコードでした。


添付ファイル: file01.png 184件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2020-04-16 (木) 22:32:59