Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#判断字符串为空

作者:疯狂灭世   发布日期:2025-03-16   浏览:54

// 判断字符串是否为空的几种常见方法

// 方法1: 使用 string.IsNullOrEmpty 方法
string str1 = "";
if (string.IsNullOrEmpty(str1))
{
    Console.WriteLine("str1 是空字符串或 null");
}

// 方法2: 使用 string.IsNullOrWhiteSpace 方法
// 这个方法不仅检查空字符串和 null,还会检查只包含空白字符的字符串
string str2 = "   ";
if (string.IsNullOrWhiteSpace(str2))
{
    Console.WriteLine("str2 是空字符串、null 或仅包含空白字符");
}

// 方法3: 手动检查字符串长度
string str3 = null;
if (str3 == null || str3.Length == 0)
{
    Console.WriteLine("str3 是 null 或空字符串");
}

解释说明:

  1. string.IsNullOrEmpty:这是最常用的方法之一,用于检查字符串是否为 null 或空字符串 ("")。
  2. string.IsNullOrWhiteSpace:这个方法更为严格,除了检查 null 和空字符串外,还会检查只包含空白字符(如空格、制表符等)的字符串。
  3. 手动检查字符串长度:虽然这种方法也能达到目的,但不如前两种方法简洁和直观。

上一篇:c#判断文件夹是否存在

下一篇:c# string.format左补0

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站