ภาพรวม
ใช้ Array ขนาด 256 (ASCII) หรือ Dictionary นับจำนวนครั้งที่แต่ละตัวอักษรปรากฏในสตริง
โค้ดตัวอย่าง: ใช้ Array (ASCII)
using System;
class Demo {
static int MAX_CHARS = 256;
static void CalculateFrequency(string s, int[] count) {
foreach (char c in s) {
count[c]++;
}
}
public static void Main() {
string s = "Football!";
int[] count = new int[MAX_CHARS];
CalculateFrequency(s, count);
Console.WriteLine($"Character frequency in '{s}':");
for (int i = 0; i < MAX_CHARS; i++) {
if (count[i] > 0) {
Console.WriteLine($"'{ (char)i }' : {count[i]} time(s)");
}
}
}
}
ผลลัพธ์
Character frequency in 'Football!':
' ' : 1 time(s)
'!' : 1 time(s)
'F' : 1 time(s)
'a' : 1 time(s)
'b' : 1 time(s)
'l' : 2 time(s)
'o' : 2 time(s)
't' : 1 time(s)
วิธีที่ทันสมัยกว่า: ใช้ LINQ GroupBy
using System;
using System.Linq;
string s = "Football!";
var freq = s
.GroupBy(c => c)
.Select(g => new { Char = g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count);
foreach (var item in freq) {
Console.WriteLine($"'{item.Char}' : {item.Count}");
}
วิธี: ใช้ Dictionary (รองรับ Unicode)
using System;
using System.Collections.Generic;
string s = "Football! 🎉";
var dict = new Dictionary<char, int>();
foreach (char c in s) {
if (dict.ContainsKey(c))
dict[c]++;
else
dict[c] = 1;
}
foreach (var kvp in dict.OrderByDescending(x => x.Value)) {
Console.WriteLine($"'{kvp.Key}' : {kvp.Value}");
}
นับเฉพาะตัวอักษร (Ignore case, ไม่รวมสัญลักษณ์)
var letterFreq = s
.Where(char.IsLetter)
.GroupBy(char.ToLower)
.Select(g => new { Char = g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count);
สรุป
| วิธี | รองรับ Unicode | ความเร็ว | ความซับซ้อน |
|---|---|---|---|
| Array[256] | ไม่ (ASCII only) | เร็วที่สุด | ต่ำ |
| Dictionary<char,int> | ได้ | เร็ว | ปานกลาง |
| LINQ GroupBy | ได้ | ช้ากว่า | ต่ำ (อ่านง่าย) |