In this article, we will discuss the concept of C# program to count the total words in the given string
In this post, we are going to learn how to count the total number of words in the given string in C# programming language.
C# program to count the total number of words
Code to count the total number of words using for loop
The program allows the user to enter a string thereafter It counts the total words of the given string using for loop in C++ language
Program 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Program { static void Main(string[] args) { string myString = Console.ReadLine(); int wCount = 0; if (myString.Length > 0) wCount++; for (int i = 0; i < myString.Length; i++) { if (char.IsWhiteSpace(myString[i])) wCount++; } Console.WriteLine(wCount); Console.ReadLine(); } } |
Code to count the total number of words using do-while loop
The program allows the user to enter a string thereafter It counts the total words of the given string using do-while loop in C++ language
Program 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | static void Main(string[] args) { string myString = Console.ReadLine(); int wCount = 0, index = 0; while (index < myString.Length) { while (index < myString.Length && !char.IsWhiteSpace(myString[index])) index++; wCount++; while (index < myString.Length && char.IsWhiteSpace(myString[index])) index++; } Console.WriteLine(wCount); Console.ReadLine(); } |
Program 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Program { static void Main(string[] args) { string sentence; Console.Write("Enter String : "); sentence = Console.ReadLine(); string[] words = sentence.Split(' '); Console.WriteLine("Count of words :" + words.Length); Console.ReadKey(); } } |
When the above code is executed, it produces the following result