Tìm ký tự/xuất hiện nhiều nhất trong chuỗi: dùng mảng đếm (ASCII) hoặc Dictionary/LINQ GroupBy.
Ví dụ: Tìm ký tự xuất hiện nhiều nhất
using System;
using System.Linq;
class Program
{
static void Main()
{
string s = "thisisit!";
// Cách 1: LINQ GroupBy (ngắn gọn)
var mostFrequent = s
.GroupBy(c => c)
.OrderByDescending(g => g.Count())
.First();
Console.WriteLine($"Ký tự nhiều nhất: '{mostFrequent.Key}' ({mostFrequent.Count()} lần)");
// Cách 2: Dictionary (hiệu năng tốt hơn)
var counts = new Dictionary();
foreach (char c in s)
counts[c] = counts.GetValueOrDefault(c) + 1;
var max = counts.Aggregate((x, y) => x.Value > y.Value ? x : y);
Console.WriteLine($"Dictionary: '{max.Key}' ({max.Value} lần)");
// Hiển thị tất cả tần suất
Console.WriteLine("\nTất cả tần suất:");
foreach (var kvp in counts.OrderByDescending(x => x.Value))
Console.WriteLine($"'{kvp.Key}': {kvp.Value}");
}
}
Kết quả đầu ra
Ký tự nhiều nhất: 'i' (3 lần) Dictionary: 'i' (3 lần) Tất cả tần suất: 'i': 3 's': 2 't': 2 'h': 1 '!': 1
Mở rộng: Áp dụng tương tự cho mảngGroupBy(x => x).