IsNullOrEmpty 和 IsNullOrWhiteSpace
区别
IsNullOrEmpty 和 IsNullOrWhiteSpace 是用于检查字符串是否为空的两个常用方法,它们之间的区别在于对空白字符的处理:
**IsNullOrEmpty**方法:
-
IsNullOrEmpty方法用于检查字符串是否为null或者空字符串""。- 如果字符串为
null或者空字符串"",则该方法返回true;否则返回false。 - 该方法不会考虑字符串中是否包含空白字符,只关注字符串是否为空或为
null。
**IsNullOrWhiteSpace**方法:
-
IsNullOrWhiteSpace方法用于检查字符串是否为null、空字符串""或者仅包含空白字符。- 如果字符串为
null、空字符串""或者只包含空白字符(如空格、制表符、换行符等),则该方法返回true;否则返回false。 - 该方法会在检查字符串是否为空的同时,也会考虑字符串中是否包含空白字符。
1.IsNullOrEmpty 方法
using System;
class Program
{
static void Main()
{
string str1 = "Hello, World!";
string str2 = "";
string str3 = " ";
string str4 = "\t";
string str5 = "\n";
string str6 = null;
Console.WriteLine($"str1 是 null 或空白字符吗? {string.IsNullOrEmpty(str1)}"); // false
Console.WriteLine($"str2 是 null 或空白字符吗? {string.IsNullOrEmpty(str2)}"); // true
Console.WriteLine($"str3 是 null 或空白字符吗? {string.IsNullOrEmpty(str3)}"); // false
Console.WriteLine($"str4 是 null 或空白字符吗? {string.IsNullOrEmpty(str4)}"); // false
Console.WriteLine($"str5 是 null 或空白字符吗? {string.IsNullOrEmpty(str5)}"); // false
Console.WriteLine($"str6 是 null 或空白字符吗? {string.IsNullOrEmpty(str6)}"); // true
}
}

2.IsNullOrWhiteSpace 方法
using System;
class Program
{
static void Main()
{
string str1 = "Hello, World!";
string str2 = "";
string str3 = " ";
string str4 = "\t";
string str5 = "\n";
string str6 = null;
Console.WriteLine($"str1 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str1)}"); // false
Console.WriteLine($"str2 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str2)}"); // true
Console.WriteLine($"str3 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str3)}"); // true
Console.WriteLine($"str4 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str4)}"); // true
Console.WriteLine($"str5 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str5)}"); // true
Console.WriteLine($"str6 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str6)}"); // true
}
}


浙公网安备 33010602011771号