This program uses to count words in a sentence.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 | 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(); } |
Output:
Alternative Code:
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(); } |
You can find more similar examples of programming for this programming language in the site.