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

วิธีตรวจสอบอักขระ Unicode ว่าเป็นตัวอักษรหรือตัวเลขใน C#

บทความนี้สาธิตวิธีการตรวจสอบว่าอักขระ Unicode (char) ที่ระบุเป็นตัวอักษร (letter) หรือตัวเลข (decimal digit) โดยใช้ method Char.IsLetterOrDigit(char)

ตัวอย่างที่ 1: ตรวจสอบตัวเลข '1'

using System;

public class Demo
{
    public static void Main()
    {
        bool res;
        char val = '1';
        Console.WriteLine("Value = " + val);
        res = Char.IsLetterOrDigit(val);
        Console.WriteLine("Is the value a letter or digit? = " + res);
    }
}

ผลลัพธ์

Value = 1
Is the value a letter or digit? = True

ตัวอย่างที่ 2: ตรวจสอบสัญลักษณ์ '$'

using System;

public class Demo
{
    public static void Main()
    {
        bool res;
        char val = '$';
        Console.WriteLine("Value = " + val);
        res = Char.IsLetterOrDigit(val);
        Console.WriteLine("Is the value a letter or digit? = " + res);
    }
}

ผลลัพธ์

Value = $
Is the value a letter or digit? = False

คำอธิบายเพิ่มเติม

  • Char.IsLetterOrDigit(char c) คืนค่า true ถ้าตัวอักษรเป็น Letter (Lu, Ll, Lt, Lm, Lo) หรือ Decimal Digit (Nd) ตาม Unicode category
  • รวม: A-Z, a-z, 0-9, และตัวอักษร/ตัวเลขในภาษาอื่นๆ (ไทย, จีน, อาหรับ, ฯลฯ)
  • ไม่นับ: punctuation, symbol, whitespace, control characters
  • มี overload Char.IsLetterOrDigit(string s, int index)
  • เทียบเท่ากับ: Char.IsLetter(c) || Char.IsDigit(c)
  • ใช้ใน validation username, password, identifier parsing
  • Method ที่เกี่ยวข้อง: IsLetter, IsDigit, IsNumber (รวมตัวเลขทุกประเภท), IsSymbol