C#怎么判断字符串为空
判断字符串为空可以通过以下两种方式实现:
- 使用 String.IsNullOrEmpty 方法:
string str = "";
if (String.IsNullOrEmpty(str))
{
Console.WriteLine("字符串为空");
}
else
{
Console.WriteLine("字符串不为空");
}
- 直接判断字符串长度是否为 0:
string str = "";
if (str.Length == 0)
{
Console.WriteLine("字符串为空");
}
else
{
Console.WriteLine("字符串不为空");
}
两种方法都可以判断字符串是否为空。建议使用第一种方法,因为它更简单、更安全。如果字符串为 null 或空字符串,String.IsNullOrEmpty 方法都会返回 true。但是如果直接判断字符串长度是否为 0,当字符串为 null 时会抛出异常。
原文地址: https://www.cveoy.top/t/topic/boAo 著作权归作者所有。请勿转载和采集!