// 判断字符串是否为空的几种常见方法
// 方法1: 使用 string.IsNullOrEmpty 方法
string str1 = "";
if (string.IsNullOrEmpty(str1))
{
Console.WriteLine("str1 是空字符串或 null");
}
// 方法2: 使用 string.IsNullOrWhiteSpace 方法
// 这个方法不仅检查空字符串和 null,还会检查只包含空白字符的字符串
string str2 = " ";
if (string.IsNullOrWhiteSpace(str2))
{
Console.WriteLine("str2 是空字符串、null 或仅包含空白字符");
}
// 方法3: 手动检查字符串长度
string str3 = null;
if (str3 == null || str3.Length == 0)
{
Console.WriteLine("str3 是 null 或空字符串");
}
string.IsNullOrEmpty
:这是最常用的方法之一,用于检查字符串是否为 null
或空字符串 (""
)。string.IsNullOrWhiteSpace
:这个方法更为严格,除了检查 null
和空字符串外,还会检查只包含空白字符(如空格、制表符等)的字符串。上一篇:c#判断文件夹是否存在
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站