ภาพรวม
นับความถี่ของแต่ละตัวอักษรในสตริง แล้วหาค่าที่มีความถี่สูงสุด
โค้ดตัวอย่าง
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 = "thisisit!";
int[] count = new int[MAX_CHARS];
CalculateFrequency(s, count);
Console.WriteLine($"Character frequencies in '{s}':");
for (int i = 0; i < MAX_CHARS; i++) {
if (count[i] > 1) {
Console.WriteLine($"Character '{ (char)i }' : {count[i]} times");
}
}
}
}
ผลลัพธ์
Character frequencies in 'thisisit!':
Character 'i' : 3 times
Character 's' : 2 times
Character 't' : 2 times
หา Most Frequent Character (ตัวเดียว)
static char GetMostFrequentChar(string s) {
int[] count = new int[256];
foreach (char c in s) count[c]++;
int maxCount = 0;
char maxChar = '\0';
for (int i = 0; i < 256; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
maxChar = (char)i;
}
}
return maxChar;
}
วิธี LINQ (ทันสมัย)
using System.Linq;
string s = "thisisit!";
var mostFrequent = s
.GroupBy(c => c)
.OrderByDescending(g => g.Count())
.First();
Console.WriteLine($"Most frequent: '{mostFrequent.Key}' ({mostFrequent.Count()} times)");
// ทั้งหมดที่มีความถี่สูงสุด (อาจมีหลายตัว)
var maxCount = s.GroupBy(c => c).Max(g => g.Count());
var allMostFrequent = s.GroupBy(c => c).Where(g => g.Count() == maxCount).Select(g => g.Key);
รองรับ Unicode (Dictionary)
using System.Collections.Generic;
string s = "สวัสดีครับ!";
var dict = new Dictionary<char, int>();
foreach (char c in s) {
if (dict.ContainsKey(c)) dict[c]++;
else dict[c] = 1;
}
var top = dict.OrderByDescending(kvp => kvp.Value).First();
Console.WriteLine($"Most frequent: '{top.Key}' ({top.Value} times)");
กรณีพิเศษ: หลายตัวมีความถี่เท่ากันสูงสุด
string s = "aabbcc"; // a,b,c ทุกตัว 2 ครั้ง
var groups = s.GroupBy(c => c);
int maxFreq = groups.Max(g => g.Count());
var mostFrequentChars = groups.Where(g => g.Count() == maxFreq).Select(g => g.Key);
// Result: a, b, c