String.IsNullOrWhiteSpace(String) 方法

定義

表示指定字串 null是空字串,還是僅包含空白字元。

public:
 static bool IsNullOrWhiteSpace(System::String ^ value);
public static bool IsNullOrWhiteSpace(string value);
public static bool IsNullOrWhiteSpace(string? value);
static member IsNullOrWhiteSpace : string -> bool
Public Shared Function IsNullOrWhiteSpace (value As String) As Boolean

參數

value
String

要測試的字串。

傳回

true若參數valuenullEmpty或,則value為純空白字元。

範例

以下範例建立一個字串陣列,然後將陣列中的每個元素傳遞給該方法。IsNullOrWhiteSpace

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, String.Empty, "ABCDE", 
                          new String(' ', 20), "  \t   ", 
                          new String('\u2000', 10) };
      foreach (string value in values)
         Console.WriteLine(String.IsNullOrWhiteSpace(value));
   }
}
// The example displays the following output:
//       True
//       True
//       False
//       True
//       True
//       True
open System

let values = 
    [| null; String.Empty; "ABCDE"
       String(' ', 20); "  \t   "
       String('\u2000', 10) |]

for value in values do
    printfn $"{String.IsNullOrWhiteSpace value}"
// The example displays the following output:
//       True
//       True
//       False
//       True
//       True
//       True
Module Example
   Public Sub Main()
      Dim values() As String = { Nothing, String.Empty, "ABCDE", 
                                 New String(" "c, 20), "  " + vbTab + "   ", 
                                 New String(ChrW(&h2000), 10) }
      For Each value As String In values
         Console.WriteLine(String.IsNullOrWhiteSpace(value))
      Next
   End Sub
End Module
' The example displays the following output:
'       True
'       True
'       False
'       True
'       True
'       True

備註

IsNullOrWhiteSpace 是一種方便的方法,類似以下程式碼,但效能更優異:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
String.IsNullOrEmpty value || value.Trim().Length = 0
Return String.IsNullOrEmpty(value) OrElse value.Trim().Length = 0

空白字元由 Unicode 標準定義。 該IsNullOrWhiteSpace方法將任何在傳遞給true方法時回傳 的Char.IsWhiteSpace字元解讀為空白字元。

適用於

另請參閱