Beginner ยท strings
Word Count
One line of text in, the number of words out. Simple โ until the input has extra spaces, which is exactly what the hidden tests include.
Problem
Input: one line of text (letters and spaces only, up to 10,000 characters).
Output: the number of words โ pieces separated by spaces, ignoring empty ones.
Sample:
| Input | Output |
|---|---|
hello world | 2 |
the quick brown fox | 4 |
Your solution
Custom input for "Run my input"
Judging runs entirely in your browser against hidden tests. Your code is saved locally as you type. Ctrl+Enter judges.
Stuck? Hints
Hint 1 โ split, then count
line.Split(' ') gives you an array of pieces. Its Length would be one answer โ but only if there are no repeated spaces.
Hint 2 โ the empty-piece trap
Two spaces in a row produce an empty string in the array. Count only pieces with Length > 0 in a foreach. The hidden tests include lines of nothing but spaces.
Solution (try first!)
string[] words = Console.ReadLine().Split(' ');
int count = 0;
foreach (string w in words)
{
if (w.Length > 0) count++;
}
Console.WriteLine(count);
This is the first problem where the naive answer is wrong for a whole class of inputs โ the discipline of asking "what does the edge case look like?" is the real lesson.