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

เมธอด Char.IsControl(String, Int32) ใน C#

ภาพรวม

เมธอด Char.IsControl(String, Int32) ใน C# ใช้ตรวจสอบว่าตัวอักษรที่ตำแหน่งที่ระบุในสตริงเป็นตัวควบคุม (control character) หรือไม่ ตัวควบคุมคือตัวอักษรที่ไม่สามารถพิมพ์ได้และใช้ควบคุมอุปกรณ์หรือรูปแบบข้อความ เช่น newline, tab, carriage return, เป็นต้น

ไวยากรณ์

public static bool IsControl(string str, int index);

พารามิเตอร์

  • str - สตริงที่ต้องการตรวจสอบ
  • index - ตำแหน่งของตัวอักษรในสตริง (เริ่มจาก 0)

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

using System;
using System.Globalization;

public class Demo
{
    public static void Main()
    {
        string val = "hjk9878hj";
        Console.WriteLine("สตริง = " + val);
        
        // ตรวจสอบหมวดหมู่ Unicode ที่ดัชนี 4 (ตัวอักษร '7')
        UnicodeCategory unicode = Char.GetUnicodeCategory(val, 4);
        Console.WriteLine("หมวดหมู่ Unicode ที่ดัชนี 4 = " + unicode);
        
        // ตรวจสอบว่าตัวอักษรที่ดัชนี 4 เป็น control character หรือไม่
        bool result = Char.IsControl(val, 4);
        
        if (result)
            Console.WriteLine("พบตัวควบคุม!");
        else
            Console.WriteLine("ไม่พบตัวควบคุม");
    }
}

ผลลัพธ์

สตริง = hjk9878hj
หมวดหมู่ Unicode ที่ดัชนี 4 = DecimalDigitNumber
ไม่พบตัวควบคุม

ตัวอย่างเพิ่มเติม: ตรวจสอบตัวควบคุมจริง

using System;

public class Demo
{
    public static void Main()
    {
        string text = "Hello\nWorld\t!";
        
        for (int i = 0; i < text.Length; i++)
        {
            bool isControl = Char.IsControl(text, i);
            Console.WriteLine($"ดัชนี {i}: '{text[i]}' (U+{(int)text[i]:X4}) -> Control: {isControl}");
        }
    }
}

ผลลัพธ์ตัวอย่างเพิ่มเติม

ดัชนี 0: 'H' (U+0048) -> Control: False
ดัชนี 1: 'e' (U+0065) -> Control: False
ดัชนี 2: 'l' (U+006C) -> Control: False
ดัชนี 3: 'l' (U+006C) -> Control: False
ดัชนี 4: 'o' (U+006F) -> Control: False
ดัชนี 5: '
' (U+000A) -> Control: True
ดัชนี 6: 'W' (U+0057) -> Control: False
ดัชนี 7: 'o' (U+006F) -> Control: False
ดัชนี 8: 'r' (U+0072) -> Control: False
ดัชนี 9: 'l' (U+006C) -> Control: False
ดัชนี 10: 'd' (U+0064) -> Control: False
ดัชนี 11: '
' (U+0009) -> Control: True
ดัชนี 12: '!' (U+0021) -> Control: False

ตัวควบคุมทั่วไป (Common Control Characters)

รหัสชื่อคำอธิบาย
U+0009Tab (\t)แท็บแนวนอน
U+000ALine Feed (\n)บรรทัดใหม่ (Unix/Linux)
U+000DCarriage Return (\r)กลับต้นบรรทัด (Windows: \r\n)
U+000CForm Feed (\f)ข้ามหน้า
U+001BEscapeอีสเคป (ANSI escape codes)

ข้อสังเกตสำคัญ

  • มี overload อีกแบบคือ Char.IsControl(char) สำหรับตรวจสอบตัวอักษรเดี่ยว
  • ใช้ร่วมกับ Char.GetUnicodeCategory() เพื่อดูรายละเอียดหมวดหมู่ (จะได้ Control, Format, Surrogate, เป็นต้น)
  • เหมาะสำหรับการทำความสะอาดข้อมูล (sanitize input) หรือวิเคราะห์ข้อความ