今天我們一起來探討C#中常用的字串判空IsNullOrWhiteSpace的幾種方法。該方法用於檢查字串是否為null、空字串("")或只包含空白字元。如果字串為null、長度為判空或只包含空白字元(例如空格、制表符、換行符),返回true;否則返回false。與IsNullOrEmpty不同,IsNullOrWhiteSpace會考慮字串中的空白字元。
判斷字串為空有好幾種方法:
方法一: 程式碼如下:
staticvoidMain(string[] args)
{
string str = "";
if (str == "")
{
Console.WriteLine("a is empty"); ;
}
Console.ReadKey();
}
執行結果:a is empty
這樣針對str = ""也是可以的,但是大多數場景是在方法的 入口處判空,這個字串有可能是null,也有可能是" ",甚至是"\n",上面這種判空方法顯示不能覆蓋這麽多場景;
方法二 :這時候 IsNullOrEmpty就橫空出世了,針對字串值為 string .Empty、 str2 = ""、null,都可以用
staticvoidMain(string[] args)
{
string str1 = string.Empty;
if (string.IsNullOrEmpty(str1))
{
Console.WriteLine("str1 is empty"); ;
}
string str2 = "";
if (string.IsNullOrEmpty(str2))
{
Console.WriteLine("str2 is empty"); ;
}
string str3 = null;
if (string.IsNullOrEmpty(str3))
{
Console.WriteLine("str3 is empty"); ;
}
Console.ReadKey();
}
執行結果如下:
方法三 :但是
IsNullOrEmpty在字串為" ","\n","\t",時候就無能為力了,為了覆蓋這些場景,高手們一般判空使用方法IsNullOrWhiteSpace
staticvoidMain(string[] args)
{
string str1 = string.Empty;
if (string.IsNullOrWhiteSpace(str1))
{
Console.WriteLine("str1 is empty"); ;
}
string str2 = "";
if (string.IsNullOrWhiteSpace(str2))
{
Console.WriteLine("str2 is empty"); ;
}
string str3 = null;
if (string.IsNullOrWhiteSpace(str3))
{
Console.WriteLine("str3 is empty"); ;
}
string str4 = " ";
if (string.IsNullOrWhiteSpace(str4))
{
Console.WriteLine("str4 is empty"); ;
}
string str5 = "\n";
if (string.IsNullOrWhiteSpace(str5))
{
Console.WriteLine("str5 is empty"); ;
}
string str6 = "\t";
if (string.IsNullOrWhiteSpace(str6))
{
Console.WriteLine("str6 is empty"); ;
}
Console.ReadKey();
}
執行結果:
進群學習交流加 : mm1552923
如果喜歡我的文章,那麽
「 在看 」和 轉發 是對我最大的支持!