Problem overview
This version counts characters. countChars takes an Array[String] of lines and returns the sum of the line lengths as an Int. The newlines that would separate the lines in a file are not counted, and a space or a tab inside a line counts as one character like any other. The input is plain ASCII.
For ["hello", "world"] the lines have 5 and 5 characters, so the answer is 10. An empty line adds 0 and an empty array gives 0.
The real wc counts newlines too (and, with -c, bytes instead of characters). This lesson uses the simpler rule: add up the line lengths.
Approach
This is the smallest of the three counters. The previous version had to decide what a word is; here nothing needs deciding, because the number of characters in a line is already the line's length. So the function is a running total over the array: start at zero, add each line's length, return the total.
Whitespace needs no special handling. For the lines "a b\tc", "" and "xy" the lengths are 5, 0 and 2 (the tab is one character), and the function returns 7. Don't trim the lines: trimming would remove characters that the count is supposed to include.
Step by step
- Create the total. A
varnamedtotal, starting at 0. - Loop over the lines with
for (line <- lines). - Add the length. Each pass adds
line.lengthtototal. - Return the total after the loop. If it were inside the loop, the function would stop after the first line.
The solution in Scala
class Solution {
def countChars(lines: Array[String]): Int = {
var total = 0
for (line <- lines) {
total += line.length
}
return total
}
}
Some details to notice:
- The parameter is an
Array[String]. A ScalaArrayhas a fixed size and can be looped over withforexactly like aList. line.lengthis a method call written without parentheses. It counts the 16-bit units of the string; for plain ASCII text that is the same as the number of characters, which is why the lesson restricts the input to ASCII.totalis anInt, which is 32 bits and wraps silently on overflow. That would take more than two billion characters, far more than this lesson's inputs hold.- A
varis needed becausetotalis updated with+=; avalwould not compile.
Complexity
The function visits each line once and reads its length, which takes constant time for a string, so the time is O(n) in the number of lines. It keeps one integer, so the extra space is O(1).
Edge cases and common mistakes
- Counting the separators.
["hello", "world"]gives 10, not 11. The newline between the lines is not part of any line. - Trimming. Leading and trailing spaces count here. The word counter had to ignore them; this one must not.
- Returning inside the loop. That returns the length of the first line only.
- Mixing up lines and characters.
lines.lengthis the number of lines, whileline.lengthis the length of one line.
Testing
| Input | Result |
|---|---|
Array("hello", "world") | 10 |
Array("a b\tc", "", "xy") | 7 |
Array() of strings | 0 |
