Problem overview
This version of wc counts characters. The function count_chars receives a Vec<String> of lines and returns the total length of all lines as an i32. The lesson uses a simple convention: only the characters inside each line count, and the newlines that separate lines are not included. Spaces and tabs count as one character each.
For lines = ["hello", "world"] the answer is 10, since each word has 5 characters. An empty line adds 0, and an empty list of lines gives 0. The input is plain ASCII text.
Approach: add up the line lengths
The answer is the sum of the lengths of the lines, so the structure is the same as in the word counter: a running total that starts at zero and grows by one amount per line. Only the amount changes. The word counter added the number of words in each line, and this version adds the line's length.
In Rust, len() on a String returns the number of bytes in its UTF-8 encoding, not the number of characters. For ASCII text the two are the same, because every ASCII character takes exactly one byte. That is why len() is enough here, and why the lesson states that the input is ASCII.
This lesson visits the lines by position instead of borrowing the vector. The loop variable i runs over 0..lines.len(), and lines[i] is the line at that position.
Step by step
- Create the running total. Declare it with
let mutand start it at 0: no line has been counted yet, and the value will change as the loop runs. - Loop over the positions.
for i in 0..lines.len()givesievery value from 0 up to the last valid index. The range excludes its upper end, so there is no off-by-one at the end of the vector. - Add the length of the current line.
lines[i].len()is the number of bytes in that line. It is ausize, soas i32converts it to match the total. - Return the total after the loop. It sits outside the loop so that it runs once, when all lines have been added.
The solution in Rust
impl Solution {
fn count_chars(lines: Vec<String>) -> i32 {
let mut total = 0;
for i in 0..lines.len() {
total += lines[i].len() as i32;
}
return total;
}
}
Rust details worth knowing:
len()returnsusize. The function must return ani32, and Rust never converts integer types implicitly, so theas i32is needed. The compiler infers thattotalis ani32from this+=.- Bytes against characters. The word
"héllo"has 5 characters, but"héllo".len()is 6, becauseétakes two bytes in UTF-8. To count characters in general you would writes.chars().count(), which walks the string, decoding as it goes. The lesson's text is ASCII, so both give the same answer here. - Indexing the vector.
lines[i]reads the element at positioniand panics ifiis out of range. Looping over0..lines.len()keeps every index valid. The expression doesn't move the string out of the vector: callinglen()on it only borrows it. - Looping by position or by reference.
for line in &lineswould give the same result with no indexing. The index version is useful when you also need the position, and it makes the "line at positioni" picture explicit.
Complexity
Time: O(n), where n is the number of lines. A String stores its length, so len() takes constant time, and the loop does constant work per line.
Space: O(1). The only extra value is the integer total.
Edge cases and common mistakes
- Counting the separators. The lesson does not add one character per line for the newline. For
["hello", "world"]the answer is 10, not 11. - Empty input. An empty vector never enters the loop, so the function returns 0. An empty string adds 0 as well.
- Whitespace. Spaces and tabs are characters like any other.
["a b", "", "\tx"]gives 5: three characters, none, then two. - Non-ASCII text. This solution counts bytes. For
["héllo"]it returns 6, not 5. That is correct for the lesson's ASCII input, but a character count for arbitrary text would usechars().count(). - Using the wrong range.
0..=lines.len()would include one index too many and panic on the last pass.
Testing
These inputs and the results the function returns for them are worth trying:
["hello", "world"]gives 10.["a b", "", "\tx"]gives 5.[""]gives 0.- An empty vector gives 0.
["héllo"]gives 6, which shows the byte count.
