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

相关推荐
橙淮8 小时前
并发编程(六)
java·jvm
拽着尾巴的鱼儿8 小时前
springboot openfeign 自定义feign 接口重试机制
java·spring boot·后端
kyriewen8 小时前
微软用Go重写TypeScript编译器,速度提升10倍,网友:这是“背叛”还是“救赎”?
前端·typescript·ecmascript 6
白露与泡影9 小时前
2026大厂Java面试题大全!牛客网最新版
java·开发语言
Ceelog9 小时前
久坐党自救指南:屏幕前 8 小时,身体到底在经历什么
前端·后端
西陵9 小时前
Agent 为什么会陷入 Doom Loop?OpenClaw 的破解之道
前端·人工智能·ai编程
Hyyy9 小时前
普通前端续命周报——第2周
前端
EntyIU9 小时前
JVM内存与GC笔记
java·jvm·笔记
wuxinyan12310 小时前
工业级大模型学习之路030:Streamlit 企业级智能体前端工作台
前端·学习·streamlit·智能体
XS03010610 小时前
并发编程 六
java·后端