#author("2020-04-16T22:32:50+09:00","","") #navi(../) * スペースのみの文字列、空の文字列、サイズ0の文字列を判定する [#dfe0a770] 半角スペースのみの文字列、null(Nothing)な文字列、サイズ0の文字列を判定する C#, Visual Basic のサンプルコードを紹介します。~ Stringクラスには半角スペースのみ、空の文字列、サイズ0の文字列を判定するのに、~ ''String.IsNullOrEmpty'', ''String.IsNullOrWhiteSpace'' という便利なメソッドがあります。~ #contents * 関連サイト [#q67072ae] -[[Microsoft .NET | String>https://docs.microsoft.com/ja-jp/dotnet/api/system.string]] * 動作確認環境 [#p0dcd7d0] - Windows 10 - Visual Studio 2019 - .NET Core 3.1 - コンソールアプリケーション #htmlinsert(windev-top.html) * C#, Visual Basic サンプルコードと実行結果 [#o97acfe9] 以下に''String.IsNullOrEmpty'', ''String.IsNullOrWhiteSpace''のサンプルコード紹介と実行結果を記します。~ 文字列が条件に成立すれば、true, 不成立であれば false が返却されます。~ 実際のプログラミングでは、ifにより判定することになりますね。 ** C# [#h5bf8e17] 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 [#y0f0085f] 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 ** 実行結果 [#ab821c58] 上記のサンプルコードを実行したときのキャプチャになります。 #ref(01.png) 以上、''String.IsNullOrEmpty'', ''String.IsNullOrWhiteSpace''を使って、~ 空の文字列、サイズが0の文字列、半角スペースのみの文字列を判定するサンプルコードでした。