Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.
Function signature:
public int CountWords(List<string> lines)
Example:
Input: lines = ["hello world", "foo bar baz", ""] Output: 5
The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.
Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.
Iterate over the lines and accumulate the word count. Splitting on runs of whitespace naturally drops empty pieces, so blank or whitespace-only lines contribute zero.
Split each line on whitespace with
StringSplitOptions.RemoveEmptyEntries so consecutive spaces collapse and empty lines yield no tokens, then count:
total += line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length;
The full solution:
class Solution {
public int CountWords(List<string> lines) {
int total = 0;
foreach (string line in lines) {
total += line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length;
}
return total;
}
}
Free plan: 30 tutor messages. Premium is unlimited.
