स्ट्रिंग में प्रत्येक कैरेक्टर की आवृत्ति (फ्रीक्वेंसी) गिनने के लिए हम प्रत्येक अद्वितीय कैरेक्टर के लिए उसकी घटनाएं गिनते हैं।
उदाहरण: क्रमिक दृष्टिकोण
using System;
public class Demo {
public static void Main() {
string str = "Website";
Console.WriteLine("String: " + str);
while (str.Length > 0) {
Console.Write(str[0] + " = ");
int count = 0;
for (int j = 0; j < str.Length; j++) {
if (str[0] == str[j]) {
count++;
}
}
Console.WriteLine(count);
// प्रोसेस किए गए कैरेक्टर को हटा दें
str = str.Replace(str[0].ToString(), string.Empty);
}
Console.ReadLine();
}
}
आउटपुट
String: Website W = 1 e = 2 b = 1 s = 1 i = 1 t = 1
बेहतर दृष्टिकोण: Dictionary का उपयोग (O(n))
using System; using System.Collections.Generic; string str = "Website"; var freq = new Dictionary(); foreach (char c in str) { if (freq.ContainsKey(c)) freq[c]++; else freq[c] = 1; } foreach (var kvp in freq) { Console.WriteLine($"{kvp.Key} = {kvp.Value}"); }
LINQ GroupBy के साथ (सबसे संक्षिप्त)
using System.Linq;
var freq = str.GroupBy(c => c)
.ToDictionary(g => g.Key, g => g.Count());
// या सीधे प्रिंट
foreach (var g in str.GroupBy(c => c)) {
Console.WriteLine($"{g.Key} = {g.Count()}");
}
सरणी-आधारित (केवल ASCII के लिए, सबसे तेज)
int[] counts = new int[256]; // ASCII के लिए
foreach (char c in str) {
counts[c]++;
}
for (int i = 0; i < 256; i++) {
if (counts[i] > 0)
Console.WriteLine($"{(char)i} = {counts[i]}");
}
केस-इनसेंसिटिव गिनती
var freq = str.ToLower()
.GroupBy(c => c)
.ToDictionary(g => g.Key, g => g.Count());
मुख्य बिंदु
- मूल दृष्टिकोण O(n²) है - प्रत्येक अद्वितीय कैरेक्टर के लिए पूरी स्ट्रिंग स्कैन करता है।
DictionaryयाGroupByO(n) है - बड़े स्ट्रिंग्स के लिए बहुत तेज।Replaceहर बार नई स्ट्रिंग बनाता है - मेमोरी अक्षम।- यूनिकोड स्ट्रिंग्स के लिए Dictionary/GroupBy आवश्यक है (सरणी 65536+ आकार की होगी)।