C# program to Count words in a given string


Let’s say we want to count the number of words in the following string −

str1 = "Hello World!";

Now you need to loop though till string length and increment the variable count on finding “ “,
, \t as shown below −

if(str1[a]==' ' || str1[a]=='
' || str1[a]=='\t') {    count++; }

You can try to run the following code to count words in a given string in C#.

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {
      string str1;
      int a, count;
      str1 = "Hello World!";
      a = 0;
      count = 1;
      while (a <= str1.Length - 1) {
         if(str1[a]==' ' || str1[a]=='
' || str1[a]=='\t') {             count++;          }          a++;       }       Console.Write("Total words= {0}
", count);    } }

Output

Total words= 2

Updated on: 23-Jun-2020

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements