Đếm tần suất ký tự trong chuỗi dùng mảng
Cách 1: Mảng cho ASCII (nhanh nhất)
using System;
class Program
{
static void Main()
{
string s = "Football!";
int[] freq = new int[256];
foreach (char c in s)
freq[c]++;
Console.WriteLine("Tần suất ký tự (ASCII):");
for (int i = 0; i < 256; i++)
{
if (freq[i] > 0)
Console.WriteLine($"'{((char)i)}': {freq[i]} lần");
}
}
}
Cách 2: Dictionary cho Unicode (linh hoạt)
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
string s = "Xin chào Việt Nam!";
var freq = new Dictionary();
foreach (char c in s)
{
if (char.IsWhiteSpace(c)) continue; // Bỏ qua khoảng trắng nếu muốn
freq[c] = freq.GetValueOrDefault(c) + 1;
}
Console.WriteLine("Tần suất (sắp xếp theo ký tự):");
foreach (var kvp in freq.OrderBy(x => x.Key))
Console.WriteLine($"'{kvp.Key}': {kvp.Value}");
Console.WriteLine("\nSắp xếp theo tần suất giảm dần:");
foreach (var kvp in freq.OrderByDescending(x => x.Value))
Console.WriteLine($"'{kvp.Key}': {kvp.Value}");
}
}
Kết quả đầu ra (ASCII)
Tần suất ký tự (ASCII): '!': 1 lần 'F': 1 lần 'a': 1 lần 'b': 1 lần 'l': 2 lần 'o': 2 lần 't': 2 lần
Mở rộng: Để đếm từ (word frequency), dùng Split hoặc Regex tách từ, sau đó GroupBy.