C# 字符串判断是否为空IsNullOrEmpty()和IsNullOrWhiteSpace()

结论

IsNullOrEmpty 和 IsNullOrWhiteSpace,这两个方法都可以用于判断一个字符串是否为空 "" 或者为 null

IsNullOrWhiteSpace 还可识别只包含空格 的字符串

IsNullOrEmpty()

先判断是否为 null,如果不是 null,再判断是否为"" 空字符串

语法

public static bool IsNullOrEmpty(string value);

例子

string str1 = null;
string str2 = "";
string str3 = "hello world";

if (string.IsNullOrEmpty(str1))
{
    Console.WriteLine("str1 is empty or null");
}
if (string.IsNullOrEmpty(str2))
{
    Console.WriteLine("str2 is empty or null");
}
if (string.IsNullOrEmpty(str3))
{
    Console.WriteLine("str3 is empty or null");
}

执行结果:

str1 is empty or null
str2 is empty or null

IsNullOrWhiteSpace()

是静态方法,如果传入的字符串为空 ""、为 null 或者只包含空格 `,该方法将返回true,否则返回false`

语法

public static bool IsNullOrWhiteSpace(string value);

例子

string str1 = null;
string str2 = "";
string str3 = "  ";
string str4 = "hello world";

if (string.IsNullOrWhiteSpace(str1))
{
    Console.WriteLine("str1 is null, empty, or whitespace");
}
if (string.IsNullOrWhiteSpace(str2))
{
    Console.WriteLine("str2 is null, empty, or whitespace");
}
if (string.IsNullOrWhiteSpace(str3))
{
    Console.WriteLine("str3 is null, empty, or whitespace");
}
if (string.IsNullOrWhiteSpace(str4))
{
    Console.WriteLine("str4 is null, empty, or whitespace");
}

输出如下:

str1 is null, empty, or whitespace
str2 is null, empty, or whitespace
str3 is null, empty, or whitespace

参考:
https://blog.csdn.net/Wod_7/article/details/131274171