C# program to count number of words in a String
Here's a C# program that counts the number of words in a given string:
using System;
class Program
{
static void Main()
{
string inputString = "Hello, World! This is a sample string.";
int wordCount = CountWords(inputString);
Console.WriteLine("Number of words in the string: " + wordCount);
}
static int CountWords(string inputString)
{
// Remove leading and trailing whitespace
inputString = inputString.Trim();
int wordCount = 0;
// Iterate through each character in the string
for (int i = 0; i < inputString.Length; i++)
{
// If current character is a whitespace and the next character is not a whitespace, increment word count
if (inputString[i] == ' ' && i + 1 < inputString.Length && inputString[i + 1] != ' ')
{
wordCount++;
}
}
// Add 1 to account for the last word in the string
wordCount++;
return wordCount;
}
}
In this program, the 'CountWords' method takes an input string and returns the number of words in it.
First, we use the 'Trim' method to remove any leading and trailing whitespace from the string. This ensures that we don't count extra words due to whitespace at the beginning or end.
Next, we initialize a 'wordCount' variable to 0. Then, we iterate through each character in the string using a 'for' loop. If the current character is a whitespace and the next character is not a whitespace (to avoid counting consecutive whitespaces as separate words), we increment the 'wordCount' variable.
Finally, we add 1 to the 'wordCount' to account for the last word in the string. This is necessary because if the last word is not followed by a whitespace, it wouldn't have been counted in the loop.
The program output for the given input string would be:
Number of words in the string: 7
The string "Hello, World! This is a sample string." contains 7 words.