Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# ตรวจสอบสตริงสำหรับอักขระ whitespace หรือ null

เมธอด string.IsNullOrWhiteSpace() คืนค่า true หากสตริงเป็น null, ว่าง ("") หรือประกอบด้วยอักขระ whitespace เท่านั้น (ช่องว่าง, แท็บ, บรรทัดใหม่ เป็นต้น)

ตัวอย่างการใช้งาน

bool val1 = string.IsNullOrWhiteSpace("100"); // false - มีตัวเลข
bool val2 = string.IsNullOrWhiteSpace(" ");   // true  - ช่องว่าง
bool val3 = string.IsNullOrWhiteSpace(null);  // true  - null

ตัวอย่างโค้ดเต็ม

using System;

public class Demo
{
    public static void Main()
    {
        bool val1 = string.IsNullOrWhiteSpace("100");
        bool val2 = string.IsNullOrWhiteSpace(" ");
        bool val3 = string.IsNullOrWhiteSpace(null);
        Console.WriteLine(val1); // False
        Console.WriteLine(val2); // True
        Console.WriteLine(val3); // True
    }
}

ผลลัพธ์

False
True
True

แตกต่างจาก IsNullOrEmpty: IsNullOrEmpty ตรวจสอบเฉพาะ null หรือ "" ไม่รวม whitespace