IsNullOrEmpty 和 IsNullOrWhiteSpace

区别

IsNullOrEmptyIsNullOrWhiteSpace 是用于检查字符串是否为空的两个常用方法,它们之间的区别在于对空白字符的处理:

  1. **IsNullOrEmpty** 方法
    • IsNullOrEmpty 方法用于检查字符串是否为 null 或者空字符串 ""
    • 如果字符串为 null 或者空字符串 "",则该方法返回 true;否则返回 false
    • 该方法不会考虑字符串中是否包含空白字符,只关注字符串是否为空或为 null
  1. **IsNullOrWhiteSpace** 方法
    • IsNullOrWhiteSpace 方法用于检查字符串是否为 null、空字符串 "" 或者仅包含空白字符。
    • 如果字符串为 null、空字符串 "" 或者只包含空白字符(如空格、制表符、换行符等),则该方法返回 true;否则返回 false
    • 该方法会在检查字符串是否为空的同时,也会考虑字符串中是否包含空白字符。

1.IsNullOrEmpty 方法

using System;

class Program
{
    static void Main()
    {
        string str1 = "Hello, World!";
        string str2 = "";
        string str3 = "   ";
        string str4 = "\t";
        string str5 = "\n";
        string str6 = null;

        Console.WriteLine($"str1 是 null 或空白字符吗? {string.IsNullOrEmpty(str1)}"); // false
        Console.WriteLine($"str2 是 null 或空白字符吗? {string.IsNullOrEmpty(str2)}"); // true
        Console.WriteLine($"str3 是 null 或空白字符吗? {string.IsNullOrEmpty(str3)}"); // false
        Console.WriteLine($"str4 是 null 或空白字符吗? {string.IsNullOrEmpty(str4)}"); // false
        Console.WriteLine($"str5 是 null 或空白字符吗? {string.IsNullOrEmpty(str5)}"); // false
        Console.WriteLine($"str6 是 null 或空白字符吗? {string.IsNullOrEmpty(str6)}"); // true
    }
}

img

2.IsNullOrWhiteSpace 方法

using System;

class Program
{
    static void Main()
    {
        string str1 = "Hello, World!";
        string str2 = "";
        string str3 = "   ";
        string str4 = "\t";
        string str5 = "\n";
        string str6 = null;

        Console.WriteLine($"str1 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str1)}"); // false
        Console.WriteLine($"str2 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str2)}"); // true
        Console.WriteLine($"str3 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str3)}"); // true
        Console.WriteLine($"str4 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str4)}"); // true
        Console.WriteLine($"str5 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str5)}"); // true
        Console.WriteLine($"str6 是 null 或空白字符吗? {string.IsNullOrWhiteSpace(str6)}"); // true
    }
}

img

posted @ 2024-04-23 10:20  好大的鱼  阅读(521)  评论(0)    收藏  举报