Problem overview
CountWords takes a List<string> of lines and returns the total number of words in all of them, like wc -w does for a file. A word is a run of characters between spaces or tabs.
For ["hello world", "foo bar baz", ""] the lines hold 2, 3 and 0 words, so the method returns 5. Extra spaces at either end of a line, or several spaces in a row, never create words. A line that is empty or only whitespace counts 0, and an empty list gives 0.
Approach
Counting words means counting the pieces left after cutting each line at its whitespace. You could walk through the characters and track whether you are inside a word, but C# can do the cutting for you: Split returns an array of the pieces, and the array's Length is the count. Do this for every line and add the numbers up.
The only subtlety is what Split does with gaps. Splitting " a b " on a single space gives 6 pieces, most of them empty strings. Splitting it with StringSplitOptions.RemoveEmptyEntries gives 2, which is the right word count. Splitting an empty string with the option gives 0 pieces, so blank lines need no special case.
Step by step
- Create
total. Anintthat starts at 0 and collects the words of every line. - Loop with
foreach. It gives you eachstring lineof the list directly, with no index to manage. - Add the line's word count. Split the line and add the
Lengthof the resulting array tototal. - Return
totalafter the loop, once, when every line has been counted.
The solution in C#
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;
}
}
The details worth knowing:
(char[])nullmeans "any whitespace". When the separator array isnull,Splitcuts at every whitespace character, so tabs and spaces both work. The cast is needed becauseSplithas several overloads, and a barenullwould not say which one you mean.RemoveEmptyEntriesdoes the cleanup. Without it,"a b".Split(' ')has three pieces, because of the empty one between the two spaces. With it, you get two. For"a\tb c"the result has 3 words.- The result is an array. Arrays have a
Lengthproperty, while theListof lines hasCount. Mixing the two up is a compile error. +=adds to the variable. The loop adds a different number for each line, sototalends as the sum.
Edge cases and common mistakes
- Empty and blank lines.
""and" "both split into 0 pieces, so they add nothing. - Leading and trailing whitespace.
" hello "is one word. Splitting on a single space without the option would report 5 pieces. - Counting spaces instead of words. The number of spaces plus one is wrong as soon as there are two spaces in a row or a space at an edge.
- Returning inside the loop. A
returnthere would stop after the first line. - An empty list. The loop never runs, and
totalstays 0.
Testing
["hello world", "foo bar baz", ""]gives5.[" a \t\t b ", " "]gives2.[]gives0.
