📜  C#| IsNullOrWhiteSpace()方法

📅  最后修改于: 2021-05-29 18:54:48             🧑  作者: Mango

在C#中, IsNullOrWhiteSpace()是一个字符串方法。用于检查指定的字符串是否为null或仅包含空格字符。如果尚未为字符串分配值或为字符串明确分配值为null,则该字符串将为null。

句法:

public static bool IsNullOrWhiteSpace(String str)  

说明:此方法将采用类型为System.String的参数,并且此方法将返回布尔值。如果方法的参数列表为null或String.Empty ,或仅包含空格字符,则返回True,否则返回False。

例子:

Input : str  = null         // initialize by null value
        String.IsNullOrWhiteSpace(str)
Output: True

Input : str  = " "  // initialize by whitespace
        String.IsNullOrWhiteSpace(str)
Output: True

程序:演示IsNullOrWhiteSpace()方法的工作原理:

// C# program to illustrate 
// IsNullOrWhiteSpace() Method
using System;
class Geeks {
    
    // Main Method
    public static void Main(string[] args)
    {
        string s1 = null;
  
        // for null value always return true
        bool b1 = String.IsNullOrWhiteSpace(s1);
        Console.WriteLine(b1);
  
        string s2 = " ";
  
        // for whitespace value always return true
        bool b2 = String.IsNullOrWhiteSpace(s2);
        Console.WriteLine(b2);
  
        string s4 = " \n ";
  
        // for new line value return true
        bool b4 = String.IsNullOrWhiteSpace(s4);
        Console.WriteLine(b4);
  
        string s5 = "\t";
  
        // for tab value return true
        bool b5 = String.IsNullOrWhiteSpace(s5);
        Console.WriteLine(b5);
  
        string s6 = "\r";
  
        // for carriage Return value return true
        bool b6 = String.IsNullOrWhiteSpace(s6);
        Console.WriteLine(b6);
  
        string s7 = "GFG";
  
        // for s7 it return False
        bool b7 = String.IsNullOrWhiteSpace(s7);
        Console.WriteLine(b7);
    }
}
输出:
True
True
True
True
True
False

注意:还有一个IsNullOrWhiteSpace()方法的替代代码,如下所示:

return String.IsNullOrEmpty(str) || str.Trim().Length == 0;

程序:演示IsNullOrEmpty()方法的替代方法

// C# program to illustrate the 
// similar code for IsNullOrWhiteSpace()
using System;
class Geeks {
  
    // similar code to 
    // IsNullOrWhiteSpace()
    public static bool check(string str)
    {
        return(String.IsNullOrEmpty(str) || 
              str.Trim().Length == 0) ? true : false;
    }
  
    // Main Method
    public static void Main(string[] args)
    {
        string s1 = "GeeksforGeeks";
        string s2 = " "; 
        string s3 = null;
        string s4 = " \n ";
  
        bool b1 = check(s1);
        bool b2 = check(s2);
        bool b3 = check(s3);
        bool b4 = check(s4);
  
        // To display result
        Console.WriteLine(b1);
        Console.WriteLine(b2);
        Console.WriteLine(b3);
        Console.WriteLine(b4);
    }
}
输出:
False
True
True
True

参考: https : //msdn.microsoft.com/en-us/library/system。字符串.isnullorwhitespace