w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Count the total number of words in a string

C# Sharp String: Exercise-5 with Solution

Write a program in C# Sharp to count the total number of words in a string.

C# Sharp Exercises: Count the total number of words in a string

Sample Solution:-

C# Sharp Code:

using System;  
public class Exercise5
{  
    public static void Main() 
{
    string str;
    int i, wrd,l;
	
      Console.Write("\n\nCount the total number of words in a string :\n");
      Console.Write("------------------------------------------------------\n"); 	
      Console.Write("Input the string : ");
      str = Console.ReadLine();
	
    l = 0;
    wrd = 1;

    /* loop till end of string */
    while (l <= str.Length - 1)
    {
        /* check whether the current character is white space or new line or tab character*/
        if(str[l]==' ' || str[l]=='\n' || str[l]=='\t')
        {
            wrd++;
        }

        l++;
    }

   Console.Write("Total number of words in the string is : {0}\n", wrd);
	}
}

Sample Output:

Count the total number of words in a string :                          
------------------------------------------------------                 
Input the string : w3resource is a tutorial                            
Total number of words in the string is : 4

Flowchart:

Flowchart: Count the total number of words in a string

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to print individual characters of the string in reverse order.
Next: Write a program in C# Sharp to compare two string without using string library functions.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming