स्ट्रिंग में शब्दों की गिनती के लिए हम व्हाइटस्पेस कैरेक्टर्स (स्पेस, टैब, नई लाइन) को विभाजक (डिलीमीटर) के रूप में उपयोग करते हैं।
उदाहरण: मैन्युअल लूप
using System;
public class Demo {
public static void Main() {
int index = 0, wordCount = 1; // कम से कम 1 शब्द मानकर
string str = "Hello World!";
while (index <= str.Length - 1) {
if (str[index] == ' ' || str[index] == '\n' || str[index] == '\t') {
wordCount++;
}
index++;
}
Console.Write("Number of words in the string = {0}\n", wordCount);
}
}
आउटपुट
Number of words in the string = 2
समस्याएं इस दृष्टिकोण में
- लगातार स्पेस एकाधिक शब्द गिनते हैं ("Hello World" → 3 शब्द)। <लीडिंग/ट्रेलिंग स्पेस गलत गिनती देते हैं।
- खाली स्ट्रिंग के लिए 1 लौटाता है (गलत)।
बेहतर: Split + RemoveEmptyEntries
string str = "Hello World! ";
int count = str.Split(new[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Length;
Console.WriteLine(count); // 2
सबसे अच्छा: Regex (शब्द सीमाओं के साथ)
using System.Text.RegularExpressions;
int count = Regex.Matches(str, @"\b\w+\b").Count;
// या केवल शब्द कैरेक्टर्स
int count = Regex.Matches(str, @"[\p{L}\p{N}']+").Count;
LINQ के साथ
using System.Linq;
int count = str.Split(new[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Length;
किनारे के मामले संभालना
public static int CountWords(string str) {
if (string.IsNullOrWhiteSpace(str)) return 0;
return str.Split(new[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
// टेस्ट
Console.WriteLine(CountWords("")); // 0
Console.WriteLine(CountWords(" ")); // 0
Console.WriteLine(CountWords("Hello")); // 1
Console.WriteLine(CountWords("Hello World")); // 2
Console.WriteLine(CountWords(" Hello World ")); // 2
मुख्य बिंदु
- मैन्युअल लूप त्रुटि-प्रवण है -
SplitयाRegexउपयोग करें। StringSplitOptions.RemoveEmptyEntriesलगातार डिलीमीटर्स को संभालता है।- Regex
\b\w+\bशब्द सीमाओं को सही ढंग से पहचानता है। - अपोस्ट्रोफी वाले शब्द ("don't") के लिए Regex पैटर्न समायोजित करें।