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

โปรแกรม C# ตรวจสอบ Pangram

Pangram คือประโยคที่มีตัวอักษรภาษาอังกฤษครบทุกตัว (A-Z) 26 ตัว

ตัวอย่างคลาสสิก: "The quick brown fox jumps over the lazy dog"

วิธีการ (LINQ)

static bool CheckPangram(string str) {
    return str.ToLower()
              .Where(ch => Char.IsLetter(ch))
              .GroupBy(ch => ch)
              .Count() == 26;
}

ขั้นตอน: Lowercase → กรองเฉพาะตัวอักษร → Group by ตัวอักษร → นับ distinct count → เท่ากับ 26?

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Demo {
    public class Program {
        public static void Main(string[] arg) {
            string str = "The quick brown fox jumps over the lazy dog";
            Console.WriteLine("{0}: \"{1}\" is pangram", CheckPangram(str), str);
            Console.ReadKey();
        }
        static bool CheckPangram(string str) {
            return str.ToLower().Where(ch => Char.IsLetter(ch)).GroupBy(ch => ch).Count() == 26;
        }
    }
}

ผลลัพธ์

True: "The quick brown fox jumps over the lazy dog" is pangram

วิธีทางเลือก (Bit Mask - เร็วกว่า):

int mask = 0;
foreach (char c in str.ToLower()) {
    if (c >= 'a' && c <= 'z') mask |= 1 << (c - 'a');
}
return mask == 0x3FFFFFF; // 26 bits = 1