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

相关推荐
写代码写到手抽筋7 小时前
5G上行DCI字段判定:端口 流数 PMI选择详解
java·算法·5g
xieliyu.7 小时前
Java算法精讲:双指针(二)
java·开发语言·算法
jeffer_liu8 小时前
Spring AI 生产级实战:裁判员
java·人工智能·后端·spring·大模型
云水一下8 小时前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
counterxing8 小时前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
copyer_xyf9 小时前
Python 模块与包的导入导出
前端·后端·python
研☆香9 小时前
es6新特性功能介绍(四)
前端·ecmascript·es6
小bo波9 小时前
枚举实战
java·设计模式·枚举·后端开发·代码重构
微扬嘴角9 小时前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
夜微凉49 小时前
三、Spring
java·后端·spring