判斷字符串為空有好幾種方法:
方法一:?代碼如下:
static void Main(string[] args){string str = "";if (str == ""){Console.WriteLine("a is empty"); ;}Console.ReadKey();}
運行結果:a is empty
這樣針對str = ""也是可以的,但是大多數場景是在方法的 入口處判空,這個字符串有可能是null,也有可能是" ? ",甚至是"\n",上面這種判空方法顯示不能覆蓋這么多場景;
方法二 :這時候IsNullOrEmpty就橫空出世了,針對字符串值為string.Empty、str2 = ""、null,都可以用
static void Main(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
static void Main(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();}
運行結果: