Đếm tần suất ký tự: mảng int[256] cho ASCII, Dictionary
Ví dụ đầy đủ
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
string s = "mynameistomhanks";
Console.WriteLine($"Chuỗi: \"{s}\"");
Console.WriteLine();
// Cách 1: LINQ GroupBy (ngắn gọn)
Console.WriteLine("--- LINQ GroupBy ---");
var freq = s.GroupBy(c => c)
.OrderByDescending(g => g.Count())
.ThenBy(g => g.Key);
foreach (var g in freq)
{
Console.WriteLine($"'{g.Key}': {g.Count()} {(g.Count() == 1 ? "lần" : "lần")}");
}
// Cách 2: Dictionary (hiệu năng)
Console.WriteLine("\n--- Dictionary ---");
var dict = new Dictionary();
foreach (char c in s)
dict[c] = dict.GetValueOrDefault(c) + 1;
foreach (var kvp in dict.OrderByDescending(x => x.Value).ThenBy(x => x.Key))
Console.WriteLine($"'{kvp.Key}': {kvp.Value}");
}
}
Kết quả đầu ra
Chuỗi: "mynameistomhanks" --- LINQ GroupBy --- 'm': 3 lần 'a': 2 lần 'n': 2 lần 's': 2 lần 'y': 1 lần 'e': 1 lần 'i': 1 lần 't': 1 lần 'o': 1 lần 'h': 1 lần 'k': 1 lần --- Dictionary --- 'm': 3 'a': 2 'n': 2 's': 2 'y': 1 'e': 1 'i': 1 't': 1 'o': 1 'h': 1 'k': 1
Mở rộng: Đếm từ (word frequency) - dùng Split hoặc Regex \w+ trước khi GroupBy.