Test a text statistics tool
Quick answer
Build a small function that counts whitespace-separated words and Unicode scalar values. Then test its behavior at boundaries before using it in a command-line tool.
Specify the contract
split_whitespace separates nonempty runs by Unicode whitespace; chars counts scalar values, not bytes or grapheme clusters. This definition is intentionally simple and does not model natural-language word segmentation. Keep the pure calculation separate from file input so that tests are cheap and deterministic.
fn stats(s: &str) -> (usize, usize) { (s.split_whitespace().count(), s.chars().count()) }fn main() { println!("{:?}", stats("hi café")); }Expected stdout (not executed):
(2, 7)The accented character is one scalar value in this literal.
fn stats(s: &str) -> (usize, usize) { (s.split_whitespace().count(), s.chars().count()) }fn main() { for (s, want) in [("", (0,0)), (" ", (0,2)), ("a\nb", (2,3)), ("é", (1,1))] { assert_eq!(stats(s), want); } println!("4 cases passed");}Expected stdout (not executed):
4 cases passedEmpty, whitespace-only and non-ASCII cases protect the stated contract.
Common mistake
Do not call .len() a character count for UTF-8 text.
Try it yourself
Extend stats to count bytes too and add a test showing the difference for é.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Test a text statistics tool — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Text contains an accented scalar encoded with multiple bytes. What does chars().count() count?
Test a text statistics tool — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn stats(s: &str) -> (usize, usize) { (s.split_whitespace().count(), s.chars().count()) } fn main() { println!("{:?}", stats("hi café")); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Test a text statistics tool — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn stats(s: &str) -> (usize, usize) { (s.split_whitespace().count(), s.chars().count()) } fn main() { for (s, want) in [("", (0,0)), (" ", (0,2)), ("a\nb", (2,3)), ("é", (1,1))] { assert_eq!(stats(s), want); } println!("4 cases passed"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.