स्ट्रिंग में किसी विशिष्ट शब्द/सबस्ट्रिंग की घटनाओं (occurrences) की गिनती के लिए IndexOf मेथड का उपयोग करके लूप में खोज की जाती है।
उदाहरण
using System;
class Program {
static void Main() {
string str = "Hello World! Hello!";
Console.WriteLine("Occurrence: " + Check.CheckOccurrences(str, "Hello"));
}
}
public static class Check {
public static int CheckOccurrences(string str1, string pattern) {
int count = 0;
int index = 0;
while ((index = str1.IndexOf(pattern, index)) != -1) {
index += pattern.Length; // मिले पैटर्न के बाद से खोज जारी रखें
count++;
}
return count;
}
}
आउटपुट
Occurrence: 2
एल्गोरिदम व्याख्या
IndexOf(pattern, startIndex)-startIndexसे पैटर्न खोजता है।- यदि मिलता है (≠ -1), काउंट बढ़ाएं और
startIndexको मिली स्थिति + पैटर्न लंबाई पर ले जाएं। - नहीं मिलने तक (-1) दोहराएं।
ओवरलैपिंग मिलान (उदाहरण: "aaa" में "aa")
उपरोक्त कोड ओवरलैपिंग नहीं गिनता ("aaa" में "aa" = 1)। ओवरलैपिंग के लिए:
public static int CountOverlapping(string str, string pattern) {
int count = 0;
for (int i = 0; i <= str.Length - pattern.Length; i++) {
if (str.Substring(i, pattern.Length) == pattern)
count++;
}
return count;
}
// "aaa" में "aa" → 2 (स्थिति 0 और 1)
केस-इनसेंसिटिव खोज
int count = 0;
int index = 0;
while ((index = str.IndexOf(pattern, index, StringComparison.OrdinalIgnoreCase)) != -1) {
index += pattern.Length;
count++;
}
Regex के साथ (शब्द सीमाओं के साथ)
using System.Text.RegularExpressions; int count = Regex.Matches(str, @"\bHello\b", RegexOptions.IgnoreCase).Count; // "HelloWorld" में "Hello" नहीं गिना जाएगा (शब्द सीमा \b के कारण)
LINQ के साथ (सरल लेकिन कम कुशल)
int count = str.Split(new[] { ' ', '.', '!', '?', ',' }, StringSplitOptions.RemoveEmptyEntries)
.Count(w => w.Equals("Hello", StringComparison.OrdinalIgnoreCase));
मुख्य बिंदु
IndexOfआधारित दृष्टिकोण O(n) है और ओवरलैपिंग नहीं गिनता।- शब्द-स्तरीय गिनती के लिए
Splitया Regex\bउपयोग करें। - केस-सेंसिटिविटी आवश्यकतानुसार कॉन्फ़िगर करें।
- बड़े टेक्स्ट के लिए
StringBuilderया स्ट्रीमिंग दृष्टिकोण विचार करें।