fork(29) download
  1. using System;
  2.  
  3. public class Test
  4. {
  5. static int GetWordCount(string text)
  6. {
  7. int wordCount = 0, index = 0;
  8.  
  9. // skip whitespace until first word
  10. while (index < text.Length && char.IsWhiteSpace(text[index]))
  11. index++;
  12.  
  13. while (index < text.Length)
  14. {
  15. // check if current char is part of a word
  16. while (index < text.Length && !char.IsWhiteSpace(text[index]))
  17. index++;
  18.  
  19. wordCount++;
  20.  
  21. // skip whitespace until next word
  22. while (index < text.Length && char.IsWhiteSpace(text[index]))
  23. index++;
  24. }
  25.  
  26. return wordCount;
  27. }
  28.  
  29. private static void AssertWordCount(int expectedCount, string input)
  30. {
  31. var actual = GetWordCount(input);
  32. if (actual != expectedCount)
  33. throw new Exception(string.Format("Input '{0}': expected {1}, but got {2}",
  34. input, expectedCount, actual));
  35. }
  36.  
  37. public static void Main()
  38. {
  39. foreach (var test in new[] { "", " ", " " })
  40. {
  41. AssertWordCount(0, test);
  42. }
  43.  
  44. foreach (var test in new[] { "test", " test", "test ", " test " })
  45. {
  46. AssertWordCount(1, test);
  47. }
  48.  
  49. foreach (var test in new[] { "a b", " a b", "a b ", " a b " })
  50. {
  51. AssertWordCount(2, test);
  52. }
  53.  
  54. Console.WriteLine("Passed without exceptions");
  55. }
  56. }
Success #stdin #stdout 0s 131520KB
stdin
Standard input is empty
stdout
Passed without exceptions