using System; public class Test { static int GetWordCount(string text) { int wordCount = 0, index = 0; // skip whitespace until first word while (index < text.Length && char.IsWhiteSpace(text[index])) index++; while (index < text.Length) { // check if current char is part of a word while (index < text.Length && !char.IsWhiteSpace(text[index])) index++; wordCount++; // skip whitespace until next word while (index < text.Length && char.IsWhiteSpace(text[index])) index++; } return wordCount; } private static void AssertWordCount(int expectedCount, string input) { var actual = GetWordCount(input); if (actual != expectedCount) throw new Exception(string.Format("Input '{0}': expected {1}, but got {2}", input, expectedCount, actual)); } public static void Main() { foreach (var test in new[] { "", " ", " " }) { AssertWordCount(0, test); } foreach (var test in new[] { "test", " test", "test ", " test " }) { AssertWordCount(1, test); } foreach (var test in new[] { "a b", " a b", "a b ", " a b " }) { AssertWordCount(2, test); } Console.WriteLine("Passed without exceptions"); } }