一、C#判断字符串对象是否为空的几种方式,如下:
string == "";
string == null;
string == String.Empty;
string.length == 0
string.IsNullOrEmpty( str )
string. IsNullOrWhiteSpace(object)
二、测试代码
IsNullOrEmpty函数
string str1 = "";
string str2 = " ";
string str3 = String.Empty;
string str4 = null;
if (string.IsNullOrEmpty(str1))
{
Console.WriteLine("str1");
}
if (string.IsNullOrEmpty(str2))
{
Console.WriteLine("str2");
}
if (string.IsNullOrEmpty(str3))
{
Console.WriteLine("str3");
}
if (string.IsNullOrEmpty(str4))
{
Console.WriteLine("str4");
}
Console.ReadKey();
输出结果:
IsNullOrWhiteSpace函数
string str1 = "";
string str2 = " ";
string str3 = String.Empty;
string str4 = null;
if (string.IsNullOrWhiteSpace(str1))
{
Console.WriteLine("str1");
}
if (string.IsNullOrWhiteSpace(str2))
{
Console.WriteLine("str2");
}
if (string.IsNullOrWhiteSpace(str3))
{
Console.WriteLine("str3");
}
if (string.IsNullOrWhiteSpace(str4))
{
Console.WriteLine("str4");
}
Console.ReadKey();
输出结果:
执行效率:string. IsNullOrWhiteSpace(object) > string.IsNullOrEmpty(object) > object.Length() == 0 > object == string.Empty > object == “”