String.IsNullOrEmpty()方法是String类的内置方法,用于检查字符串是否为Null或Empty?如果字符串对象未使用正确的值初始化,则将其视为“空字符串”;如果字符串对象已初始化但不包含任何值,即为其分配了值(“”),则将其视为“空字符串”。
语法:
public static bool IsNullOrEmpty(String str);
用“字符串” /“字符串”调用该方法。此处,“字符串”是“字符串”类的别名。
Parameter(s):
str –表示要检查的字符串值或字符串对象。
返回值:
bool-如果str为null或为空,则返回“ True”,否则返回“ False”。
示例
Input: string str1 = ""; string str2 = null; string str3 = "nhooo"; Function call Console.WriteLine(string.IsNullOrEmpty(str1)); Console.WriteLine(string.IsNullOrEmpty(str2)); Console.WriteLine(string.IsNullOrEmpty(str3)); Output: True True False
范例1:
using System;
class nhooo
{
static void Main()
{
// 声明字符串变量
string str1 = "";
string str2 = null;
string str3 = "nhooo";
// 检查字符串是否为空/空
Console.WriteLine(string.IsNullOrEmpty(str1));
Console.WriteLine(string.IsNullOrEmpty(str2));
Console.WriteLine(string.IsNullOrEmpty(str3));
}
}输出结果
True True False
范例2:
using System;
class nhooo
{
static void Main()
{
// 声明字符串变量
string str = "nhooo";
// 检查字符串是否为空/空
if(string.IsNullOrEmpty(str))
Console.WriteLine("str is empty or null");
else
Console.WriteLine("str is not empty or null");
//现在将null分配给字符串
str = null;
// 检查字符串是否为空/空
if(string.IsNullOrEmpty(str))
Console.WriteLine("str is empty or null");
else
Console.WriteLine("str is not empty or null");
}
}输出结果
str is not empty or null str is empty or null