C# 中判空方法 string.IsNullOrEmpty() 和 string.IsNullOrWhiteSpace() 区别

在 C# 中,string.IsNullOrEmpty 和 string.IsNullOrWhiteSpace 是用于检查字符串是否为空的两种不同方法。

  1. string.IsNullOrEmpty 方法检查字符串是否为 null 或空字符串。如果传入的字符串为 null 或长度为 0,则返回 true;否则返回 false。

    csharp 复制代码
    string str = ""; // 或者 string str = null;
    if (string.IsNullOrEmpty(str))
    {
        // 字符串为空或者为null
    }
  2. string.IsNullOrWhiteSpace 方法检查字符串是否为 null、空字符串或者只包含空格。如果传入的字符串为 null、长度为 0 或者只包含空格,则返回 true;否则返回 false。

    csharp 复制代码
    string str = "   "; // 或者 string str = null; 或者 string str = "";
    if (string.IsNullOrWhiteSpace(str))
    {
        // 字符串为空、为null或只包含空格
    }

区别在于 string.IsNullOrWhiteSpace 还会将字符串中仅包含空格的情况视为空,而 string.IsNullOrEmpty 仅检查是否为 null 或空字符串,不考虑字符串中只包含空格的情况。

相关推荐
captain3766 小时前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
jktantan7 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
前端·javascript·vue.js
Novproxy_Z7 小时前
商用代理避坑:如何识别商家拿机房 IP 冒充住宅 IP
java·网络·tcp/ip
文丑颜不良啊8 小时前
LeetCode1481~1500题目解析
java·leetcode
2601_962885728 小时前
quotes 字段全解:涨跌幅、振幅、换手率的口径与单位
java·前端·spring
excel8 小时前
encodeURI 和 encodeURIComponent 有什么区别?
前端
前端精髓8 小时前
调用openrouter的免费API模型
java·前端·javascript
步行cgn8 小时前
Spring MVC 拦截器 Interceptor 详解:从执行流程到实战应用
java·spring·mvc
文丑颜不良啊8 小时前
LeetCode1381~1400题目解析
java·leetcode
赛博守夜人9 小时前
AI安全攻防与治理之十四:AI 安全测试不能脱离传统安全,Web、API、移动端与模型攻击面的组合拳
前端·人工智能·安全