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();
        }
    }
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...