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

โครงสร้าง Char ใน C#

ภาพรวม

Char ใน C# แทนอักขระ UTF-16 (16 บิต) มีเมธอดสแตติกและอินสแตนซ์มากมายสำหรับตรวจสอบและแปลงอักขระ

เมธอดสำคัญ

เมธอดคำอธิบาย
ConvertToUtf32(Char, Char)แปลง surrogate pair UTF-16 เป็น Unicode code point
ConvertToUtf32(String, Int32)แปลงอักขระ/ surrogate pair ที่ตำแหน่งในสตริงเป็น code point
Equals(Char)ตรวจสอบเท่ากับ Char อื่น
Equals(Object)ตรวจสอบเท่ากับออบเจ็กต์
GetHashCode()คืนแฮชโค้ด
GetNumericValue(Char)แปลงอักขระตัวเลข Unicode เป็น double
IsDigit(String, Int32)ตรวจสอบอักขระที่ตำแหน่งเป็นเลขฐานสิบหรือไม่
IsLetter(Char)ตรวจสอบเป็นตัวอักษร Unicode
IsLetter(String, Int32)ตรวจสอบอักขระที่ตำแหน่งเป็นตัวอักษร
IsLetterOrDigit(Char)ตรวจสอบเป็นตัวอักษรหรือเลข
IsLetterOrDigit(String, Int32)ตรวจสอบอักขระที่ตำแหน่งเป็นตัวอักษรหรือเลข
IsLower(Char)ตรวจสอบเป็นตัวพิมพ์เล็ก
IsPunctuation(String, Int32)ตรวจสอบอักขระที่ตำแหน่งเป็นเครื่องหมายวรรคตอน

ตัวอย่าง: Char.IsSymbol

ตรวจสอบว่าอักขระเป็นสัญลักษณ์ (symbol) หรือไม่

public static bool IsSymbol(char ch);

โค้ด

using System;

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

ผลลัพธ์

Value = P
Is the value a symbol? = False

ตัวอย่าง: Char.IsWhiteSpace

ตรวจสอบว่าอักขระเป็น whitespace หรือไม่

public static bool IsWhiteSpace(char ch);

โค้ด

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

สรุป

  • Char เป็น struct แทน UTF-16 code unit
  • มีเมธอดตรวจสอบประเภทอักขระมากมาย (IsDigit, IsLetter, IsWhiteSpace, IsSymbol, IsPunctuation, ฯลฯ)
  • รองรับ surrogate pair สำหรับอักขระนอก BMP