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

ตรวจสอบสระในสตริง C# - หาว่ามีสระครบทุกตัวหรือไม่

การตรวจสอบว่าสตริงมีสระ (Vowels) ครับชุดหรือไม่ สามารถทำได้ง่ายด้วย LINQ

ตัวอย่างพื้นฐาน

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string str = "the quick brown fox jumps over the lazy dog";

        // หาสระที่ไม่ซ้ำ (Distinct)
        var vowels = str.Where(c => "aeiouAEIOU".Contains(c))
                        .Distinct()
                        .ToList();

        if (!vowels.Any())
        {
            Console.WriteLine("No vowels!");
        }
        else
        {
            Console.WriteLine($"Found {vowels.Count} distinct vowels:");
            foreach (var v in vowels)
                Console.WriteLine($"Vowel: {v}");
        }
    }
}

ผลลัพธ์

Found 5 distinct vowels:
Vowel: e
Vowel: u
Vowel: i
Vowel: o
Vowel: a

ตรวจสอบว่ามีสระครบทุกตัว (a,e,i,o,u) หรือไม่

public static bool HasAllVowels(string str)
{
    var required = new HashSet { 'a', 'e', 'i', 'o', 'u' };
    var found = str.ToLower().Where(c => required.Contains(c)).ToHashSet();
    return required.SetEquals(found);
}

// หรือแบบ One-liner
bool hasAll = "aeiou".All(v => str.ToLower().Contains(v));

นับจำนวนสระแต่ละตัว

var vowelCounts = str.ToLower()
    .Where(c => "aeiou".Contains(c))
    .GroupBy(c => c)
    .Select(g => new { Vowel = g.Key, Count = g.Count() })
    .OrderBy(x => x.Vowel);

foreach (var vc in vowelCounts)
    Console.WriteLine($"{vc.Vowel}: {vc.Count}");

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

a: 1
e: 3
i: 1
o: 4
u: 2

ประสิทธิภาพ: ใช้ HashSet Lookup O(1)

// เร็วกว่า Contains() บน String
private static readonly HashSet Vowels = new HashSet { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };

public static int CountVowels(string str)
{
    return str.Count(c => Vowels.Contains(c));
}

รองรับภาษาอื่น (Unicode Vowels)


// สำหรับภาษาไทย ต้องกำหนดชุดสระเอง
private static readonly HashSet ThaiVowels = new HashSet
{
    'ะ', 'ั', 'า', 'ำ', 'ิ', 'ี', 'ึ', 'ื', 'ุ', 'ู', 'เ', 'แ', 'โ', 'ใ', 'ไ', 'ฤ', 'ฦ'
};

กรณีใช้งานจริง

  • Text Analysis / NLP Preprocessing
  • Password Strength: บังคับให้มีสระ
  • Word Games: Scrabble, Crossword Helper
  • Data Validation: ชื่อที่ต้องมีสระ