Cloud Training (Online)




How to Count the Number of Words in a string in C# ?

Do you have a requirement where you would need to count the number of words in a string in C# ?. Here’s a code snippet showing how you can do it.

How to Count the number of words in a string in C# ?

Let’s assume that you have a string variable which holds the value “Welcome to DeveloperPublish website” as shown below , we would just loop through the entire string and check if it contains a space , tab or a new line character and increment the word count accordingly.

Below is a sample code snippet. Note that there are many other ways to find the number of words in a string like using String.Split method but this post shows one of the ways to do it.


using System;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            int index = 0, count = 1;
            string input = "Welcome to DeveloperPublish website";
            while (index <= input.Length - 1)
            {
                if (input[index] == ' ' || input[index] == '\n' || input[index] == '\t')
                {
                    count++;
                }
                index++;
            }
            Console.WriteLine("Total Words = " + count);
            Console.ReadLine();
        }
    }
}