前言
今天我们将探讨 C#中两个常用的字符串处理方法:IsNullOrEmpty 和 IsNullOrWhiteSpace。这两个方法在处理字符串时非常常见,但是它们之间存在一些细微的区别。在本文中,我们将详细解释这两个方法的功能和使用场景,并帮助您更好地理解它们之间的区别。
IsNullOrEmpty
作用
该方法用于检查字符串是否为 null 或空字符串("")。如果字符串为 null 或长度为 0,返回 true;否则返回 false。这个方法只关注字符串的长度,不考虑其中的空白字符。
源码实现
/// <summary>
/// 判断字符串是否为null或者为空字符串
/// </summary>
/// <param name="value">字符串</param>
/// <returns></returns>
public static bool IsNullOrEmpty([NotNullWhen(false)] string? value)
{
return value == null || value.Length == 0;
}
复制代码
示例
public static void Main(string[] args)
{
string str1 = null;
string str2 = "";
string str3 = " ";
string str4 = "追逐时光者";
Console.WriteLine(IsStringNullOrEmpty(str1));// 输出:True
Console.WriteLine(IsStringNullOrEmpty(str2));// 输出:True
Console.WriteLine(IsStringNullOrEmpty(str3));// 输出:False
Console.WriteLine(IsStringNullOrEmpty(str4));// 输出:False
}
public static bool IsStringNullOrEmpty(string str)
{
return string.IsNullOrEmpty(str);
}
复制代码
IsNullOrWhiteSpace
作用
该方法用于检查字符串是否为 null、空字符串("")或只包含空白字符。如果字符串为 null、长度为 0 或只包含空白字符(例如空格、制表符、换行符),返回 true;否则返回 false。与 IsNullOrEmpty 不同,IsNullOrWhiteSpace 会考虑字符串中的空白字符。
源码实现
/// <summary>
/// 字符串是否为null、空字符串或只包含空白字符
/// </summary>
/// <param name="value">字符串</param>
/// <returns></returns>
public static bool IsNullOrWhiteSpace([NotNullWhen(false)] string? value)
{
if (value == null) return true;
for (int i = 0; i < value.Length; i++)
{
//判断一个字符是否为空白字符(例如空格、制表符、换行符)
if (!char.IsWhiteSpace(value[i])) return false;
}
return true;
}
复制代码
示例
public static void Main(string[] args)
{
string str1 = null;
string str2 = "";
string str3 = " ";
string str4 = "追逐时光者";
Console.WriteLine(IsStringNullOrWhiteSpace(str1));// 输出:True
Console.WriteLine(IsStringNullOrWhiteSpace(str2));// 输出:True
Console.WriteLine(IsStringNullOrWhiteSpace(str3));// 输出:True
Console.WriteLine(IsStringNullOrWhiteSpace(str4));// 输出:False
}
public static bool IsStringNullOrWhiteSpace(string str)
{
return string.IsNullOrWhiteSpace(str);
}
复制代码
评论