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

C# 中,string.IsNullOrEmptystring.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 或空字符串,不考虑字符串中只包含空格的情况。

相关推荐
Avan_菜菜7 小时前
AI 能写代码了,为什么我反而开始要求它先写文档?
前端·github·ai编程
爱勇宝11 小时前
鸿蒙生态的下半场:开发者不只要能开发,还要能赚钱
android·前端·程序员
IT_陈寒14 小时前
SpringBoot这个自动配置坑我跳了三次
前端·人工智能·后端
kyriewen14 小时前
我用 AI 一周写完了整个项目,上线第一天就崩了——这是我踩过最贵的 5 个坑
前端·javascript·ai编程
牧艺15 小时前
从零到协同:构建类飞书在线文档系统的五个技术重难点
前端·人工智能
用户35218024547515 小时前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
红尘散仙15 小时前
想写一个像样的终端 App?试试把 React 的开发体验搬进 Rust TUI
前端·rust
袋鼠云数栈UED团队16 小时前
一套 Spec-First 的 AI 编程工作流
前端·人工智能
袋鼠云数栈前端16 小时前
一套 Spec-First 的 AI 编程工作流
前端·ai+
angerdream16 小时前
Android手把手编写儿童手机远程监控App之vue3 路由守卫
前端