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

相关推荐
HerayChen43 分钟前
HbuilderX 内存溢出报错
java·大数据·linux
雪碧聊技术1 小时前
前端项目代码发生改变,如何重新部署到linux服务器?
前端·vue3·centos7·代码更新,重新部署
程序员小白条1 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle1 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
小马爱打代码1 小时前
Spring AI:搭建自定义 MCP Server:获取 QQ 信息
java·人工智能·spring
郭涤生1 小时前
QT 架构笔记
java·数据库·系统架构
daidaidaiyu1 小时前
基于LangGraph开发复杂智能体学习一则
java·ai
wordbaby1 小时前
Expo 进阶指南:赋予 TanStack Query “原生感知力” —— 深度解析 AppState 与 NetInfo
前端·react native
Moment2 小时前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然 🤔🤔🤔
前端·后端·面试
天问一2 小时前
使用 Vue Router 进行路由定制和调用的示例
前端·javascript·vue.js