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.
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:
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?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework