C# 字符串 - IsNullOrWhiteSpace() 方法

C# 字符串的 IsNullOrWhiteSpace() 方法用于检查指定字符串是否为 null、空("")或仅包含空格(" ")。

如果字符串被赋值为 null,则该字符串被视为 null;如果字符串仅被赋值为一对空的双引号("")或 String.Empty(),则该字符串被视为空。此外,如果字符串仅包含空格,则表示该字符串仅由空格 (" ") 填充。

语法

以下是 C# 字符串的语法 IsNullOrWhiteSpace() 方法 -

public static bool IsNullOrWhiteSpace (string? value);

参数

此方法接受一个字符串值作为参数,表示要检查的字符串。

返回值

如果 value 参数为 null 或 Empty,或者 value 完全由空格组成,则此方法返回 true

示例 1:检查字符串是否为空

以下是 IsNullOrWhiteSpace() 方法检查字符串是否为空的基本示例 -

  
using System;
class Program {
   static void Main() {
      string str = "";
      bool res = string.IsNullOrWhiteSpace(str);
      if (res == true) {
         Console.WriteLine("String is empty.");
      }
      else {
         Console.WriteLine("String is neither empty nor null.");
      }
   }
}

输出

以下是输出 -

String is empty.

示例 2:检查字符串是否为空

我们来看另一个示例。这里,我们使用 IsNullOrWhiteSpace() 方法来检查字符串是否为空 -

using System;
class Program {
   static void Main() {
      string str = null;
      bool res = string.IsNullOrWhiteSpace(str);
      if (res == true) {
         Console.WriteLine("String is null");
      }
      else {
         Console.WriteLine("String is not null.");
      }
   }
}

输出

以下是输出 -

String is null

示例 3:检查字符串是否包含空格

在此示例中,我们使用 IsNullOrWhiteSpace 方法来检查字符串是否包含空格字符 -

using System;
class Program { 
   static void Main() {
      string str = "  ";
      bool res = string.IsNullOrWhiteSpace(str);
      if (res == true) {
         Console.WriteLine("String contains white-space");
      }
      else {
         Console.WriteLine("String is not null, not empty, or does not contains white-space");
      }
   }
}

输出

以下是输出 -

String contains white-space

示例 4:如果字符串包含值会怎样?

以下示例使用 IsNullOrWhiteSpace() 方法检查字符串是否为空、null 或包含空格。如果字符串既不为 null 也不为空,且不包含空格,则显示 false −

using System;
class Program {
   static void Main() {
      string str = "TutorialsPoint";
      bool res = string.IsNullOrWhiteSpace(str);
      if(res == true){
         Console.WriteLine("String is either Empty or Null");
      }
      else{
         Console.WriteLine("The string is neither Empty nor Null and does not contain white-space");
         Console.WriteLine("string value: {0}", str);
      }
   }
}

输出

以下是输出 -

The string is neither Empty nor Null and does not contain white-space
string value: TutorialsPoint

csharp_strings.html