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

การตรวจสอบว่าตัวอักษร Unicode เป็น whitespace ใน C#

ภาพรวม

Char.IsWhiteSpace(char c) ตรวจสอบว่าตัวอักษรเป็น whitespace หรือไม่ (space, tab, newline, ฯลฯ) คืนค่า bool รองรับ Unicode ทุกช่วง

ตัวอย่างที่ 1: ตรวจสอบ space character

using System;

public class Demo
{
    public static void Main()
    {
        bool res;
        char val = ' ';
        Console.WriteLine("Value = " + val);
        res = Char.IsWhiteSpace(val);
        Console.WriteLine("Is the value whitespace? = " + res);
    }
}

ผลลัพธ์

Value = 
Is the value whitespace? = True

ตัวอย่างที่ 2: ตรวจสอบตัวอักษร 'm' (ไม่ใช่ whitespace)

using System;

public class Demo
{
    public static void Main()
    {
        bool res;
        char val = 'm';
        Console.WriteLine("Value = " + val);
        res = Char.IsWhiteSpace(val);
        Console.WriteLine("Is the value whitespace? = " + res);
    }
}

ผลลัพธ์

Value = m
Is the value whitespace? = False

สรุป

  • Whitespace รวม: space (U+0020), tab (U+0009), newline (U+000A), carriage return (U+000D), และ Unicode space characters อื่นๆ
  • มี overload IsWhiteSpace(string, int index) ตรวจสอบที่ตำแหน่งในสตริง
  • ใช้สำหรับ parsing, validation, trimming input