在C#中判断字符串是否为空是一个常见的操作,常用的方法有两个:String.IsNullOrEmpty 和 String.IsNullOrWhiteSpace。它们都用于检查字符串是否为 null 或空,但在处理空白字符时有关键区别。
String.IsNullOrEmpty
这个方法用来判断一个字符串是否为 null 或者是空字符串("")。 如果字符串为 null,返回 true 如果字符串是 ""(长度为0),返回 true 如果字符串只包含空格、制表符或换行符等空白字符,返回 false示例:
string str1 = null;string str2 = "";
string str3 = " ";
Console.WriteLine(string.IsNullOrEmpty(str1)); // 输出:True
Console.WriteLine(string.IsNullOrEmpty(str2)); // 输出:True
Console.WriteLine(string.IsNullOrEmpty(str3)); // 输出:False
String.IsNullOrWhiteSpace
这个方法更严格,除了判断 null 和空字符串外,还会检测字符串是否仅由空白字符组成。 如果字符串为 null,返回 true 如果字符串是 "",返回 true 如果字符串只包含空格、制表符、换行符等空白字符,也返回 true示例:
string str1 = null;string str2 = "";
string str3 = " ";
string str4 = " \t \n ";
Console.WriteLine(string.IsNullOrWhiteSpace(str1)); // 输出:True
Console.WriteLine(string.IsNullOrWhiteSpace(str2)); // 输出:True
Console.WriteLine(string.IsNullOrWhiteSpace(str3)); // 输出:True
Console.WriteLine(string.IsNullOrWhiteSpace(str4)); // 输出:True
