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

相关推荐
就叫年华吧丶3 小时前
长文档点目录定位总是不准?一个 content-visibility + 平滑滚动引发的连环坑(Vue3 实战)
前端·javascript·算法·vue
JudithHuang3 小时前
React 路由:React Router
前端·react.js·前端框架
赵得C3 小时前
创建 SVG 图标预览页面:从零实现到解决 CORS 问题
前端·javascript·html
IT_陈寒3 小时前
Java的HashMap线程安全问题让我深夜掉光了头发
前端·人工智能·后端
驭渊的小故事3 小时前
SpringBoot 配置文件详解:properties 与 yml 从入门到实战
java·开发语言·笔记
三掌柜6663 小时前
ArkWeb 手记 04|Web 返回键别再一刀切
前端·harmonyos
Wx-bishekaifayuan3 小时前
Springcloud中学在线学习平台58883-计算机课程设计、毕业设计
java·vue.js·spring boot·学习·spring·spring cloud·课程设计
光影少年3 小时前
RN与Flutter架构区别
前端·flutter·react native·react.js·架构·node.js
一嘴一个橘子3 小时前
java 中使用 lua 脚本
java
peter67683 小时前
css学习小结
前端·css·学习