स्ट्रिंग में शब्दों की गिनती के लिए स्पेस, न्यूलाइन (\n), टैब (\t) को डिलीमीटर मानकर गिनती करें।
पूर्ण उदाहरण
using System;
public class Demo
{
public static void Main()
{
string str1 = "Hello World!";
int a = 0;
int count = 1; // कम से कम 1 शब्द (यदि स्ट्रिंग खाली नहीं)
while (a <= str1.Length - 1)
{
if (str1[a] == ' ' || str1[a] == '\n' || str1[a] == '\t')
{
count++;
}
a++;
}
Console.Write("कुल शब्द = {0}\n", count);
}
}
आउटपुट
कुल शब्द = 2
बेहतर दृष्टिकोण (प्रोडक्शन कोड के लिए)
string text = "Hello World!\nNew\tLine";
// Split के साथ (कई स्पेस हैंडल करता है)
int wordCount = text.Split(new[] {' ', '\n', '\t', '\r'}, StringSplitOptions.RemoveEmptyEntries).Length;
// Regex के साथ (यूनिकोड-अवेयर)
int wordCount2 = System.Text.RegularExpressions.Regex.Matches(text, @"\b\w+\b").Count;
मुख्य बिंदु
- मूल एल्गोरिदम: डिलीमीटर मिलने पर काउंट बढ़ाएं।
- एज केस: खाली स्ट्रिंग, अग्रणी/अंतिम स्पेस, एकाधिक लगातार स्पेस।
String.Split+StringSplitOptions.RemoveEmptyEntriesसरल और मजबूत।- जटिल टेक्स्ट के लिए Regex
\b\w+\bबेहतर।