Zig Project: Word Counter
In this project you’ll build a small command-line tool that finds out which words a text uses the most. You give it a file, it reads every word, counts them, and prints the top ten.
It’s a classic first “real” program because it touches the things almost every tool needs: command-line arguments, reading a file, splitting text, a hash map, sorting and printing a tidy report. We’ll build each piece on its own first, with fixed text so you can see exactly what it does, and then plug them together.
What you’ll build
Section titled “What you’ll build”Given this little story in story.txt:
The cat sat on the mat. The dog sat on the log."Is that MY mat?" said the dog. The cat didn't answer;cats don't answer dogs. The dog went back to the log,and the cat went back to sleep.the finished program prints:
story.txt: 41 words, 21 different
1. the 9 2. cat 3 3. dog 3 4. answer 2 5. back 2 6. log 2 7. mat 2 8. on 2 9. sat 2 10. to 2What you’ll practise:
- Writing a small iterator (a struct with a
nextmethod) that splits text into words (Zig Iterators). - Counting with
std.StringHashMapUnmanagedandgetOrPutValue(Zig HashMap). - Sorting with
std.mem.sortand your own compare function (Zig Sorting & Searching). - Reading arguments and a file, and turning errors into friendly messages and exit codes.
- Keeping track of who owns which memory, the part of this project that teaches the most.
Step 1: Set up
Section titled “Step 1: Set up”Make a folder with one source file, wordcount.zig, and the story to test with:
mkdir wordcountcd wordcountcat > story.txt <<'EOF'The cat sat on the mat. The dog sat on the log."Is that MY mat?" said the dog. The cat didn't answer;cats don't answer dogs. The dog went back to the log,and the cat went back to sleep.EOF(On Windows, just create story.txt in your editor and paste the four lines in.) The steps below are separate programs you can paste into wordcount.zig and run with zig run wordcount.zig. The last step is the full tool. Everything was checked with Zig 0.17.1.
Step 2: Split text into words
Section titled “Step 2: Split text into words”First, what’s a word? For this tool we’ll say a word is a run of letters, digits and apostrophes. Everything else (spaces, newlines, punctuation, quotes) separates words. The apostrophe matters so that didn't stays one word instead of didn and t.
The standard library has splitters like std.mem.tokenizeAny, but they need a list of separator characters, and punctuation is a long list. It’s easier to describe what is part of a word and write a tiny iterator for it. An iterator in Zig is just a struct with a next method that returns the next item, or null when there are none left:
const std = @import("std");
pub fn main() void { const text = "\"Is that MY mat?\" said the dog. The cat didn't answer;\nCafé 'au lait', 2 cups.";
var words: WordIterator = .{ .text = text }; while (words.next()) |word| { std.debug.print("[{s}] ", .{word}); } std.debug.print("\n", .{});}
/// Splits text into words: runs of letters, digits and apostrophes.const WordIterator = struct { text: []const u8, pos: usize = 0,
fn next(self: *WordIterator) ?[]const u8 { while (true) { // Skip everything that can't be part of a word. while (self.pos < self.text.len and !isWordByte(self.text[self.pos])) self.pos += 1; if (self.pos == self.text.len) return null;
const start = self.pos; while (self.pos < self.text.len and isWordByte(self.text[self.pos])) self.pos += 1;
// 'quoted' -> quoted, but keep don't and it's. const word = std.mem.trim(u8, self.text[start..self.pos], "'"); if (word.len > 0) return word; } }};
fn isWordByte(c: u8) bool { // Bytes from 0x80 up are parts of non-ASCII UTF-8 letters like é or ü. return std.ascii.isAlphanumeric(c) or c == '\'' or c >= 0x80;}Output:
[Is] [that] [MY] [mat] [said] [the] [dog] [The] [cat] [didn't] [answer] [Café] [au] [lait] [2] [cups]How next works:
posremembers where we are in the text between calls. It starts at0thanks to the default value= 0, so creating the iterator only needs.{ .text = text }.- The first inner
whileskips over separators. If that reaches the end, there are no more words, sonextreturnsnull, which ends thewhile (words.next()) |word|loop inmain. The reference calls that loop shape a while with optionals. - The second inner
whilewalks to the end of the word.self.text[start..self.pos]is a slice of the original text: no copying, just a pointer and a length. std.mem.trim(..., "'")takes quote marks off the ends, so'au lait'givesau, not'au. If a “word” was only apostrophes, it’s empty after trimming, and the outerwhile (true)goes round again to find the next one.
Step 3: Count the words
Section titled “Step 3: Count the words”Counting is the job hash maps were made for: the word is the key, the count is the value. You saw this pattern in Zig HashMap. Two details are new here:
Theandtheshould count as the same word, so we lowercase the text first.- The map stores slices into the text as keys, not copies. That’s fast, but it means the text has to stay alive as long as the map does. The
std.hash_mapsource says the same in its doc comments: key memory is managed by the caller.
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
// countWords changes the text, so it needs a copy we're allowed to change. const text = try gpa.dupe(u8, "The cat sat on the mat. The dog sat on the log."); defer gpa.free(text);
var counts: std.StringHashMapUnmanaged(u32) = .empty; defer counts.deinit(gpa);
const total = try countWords(gpa, &counts, text); std.debug.print("{d} words, {d} different\n", .{ total, counts.count() }); std.debug.print("the: {d}\n", .{counts.get("the").?}); std.debug.print("sat: {d}\n", .{counts.get("sat").?}); std.debug.print("cow: {?d}\n", .{counts.get("cow")});}
/// Lowercases `text` in place, then counts every word in it./// The map's keys point into `text`, so `text` must outlive the map.fn countWords(gpa: std.mem.Allocator, counts: *std.StringHashMapUnmanaged(u32), text: []u8) !u32 { _ = std.ascii.lowerString(text, text);
var total: u32 = 0; var words: WordIterator = .{ .text = text }; while (words.next()) |word| { const entry = try counts.getOrPutValue(gpa, word, 0); entry.value_ptr.* += 1; total += 1; } return total;}
/// Splits text into words: runs of letters, digits and apostrophes.const WordIterator = struct { text: []const u8, pos: usize = 0,
fn next(self: *WordIterator) ?[]const u8 { while (true) { // Skip everything that can't be part of a word. while (self.pos < self.text.len and !isWordByte(self.text[self.pos])) self.pos += 1; if (self.pos == self.text.len) return null;
const start = self.pos; while (self.pos < self.text.len and isWordByte(self.text[self.pos])) self.pos += 1;
// 'quoted' -> quoted, but keep don't and it's. const word = std.mem.trim(u8, self.text[start..self.pos], "'"); if (word.len > 0) return word; } }};
fn isWordByte(c: u8) bool { // Bytes from 0x80 up are parts of non-ASCII UTF-8 letters like é or ü. return std.ascii.isAlphanumeric(c) or c == '\'' or c >= 0x80;}Output:
12 words, 7 differentthe: 4sat: 2cow: nullPiece by piece:
gpa.dupe(u8, "...")copies the string literal into memory we own. A string literal is read-only, andcountWordswants to change the text, so it takes[]u8(changeable bytes). Passing the literal directly wouldn’t compile. In the real program the text comes fromreadFileAlloc, which already gives us a[]u8.std.ascii.lowerString(text, text)writes the lowercase version oftextintotextitself, in place. No extra memory. It only changes the letters A to Z;ÉstaysÉ.getOrPutValue(gpa, word, 0)finds the word’s slot, or creates it with the value0if the word is new. Thenentry.value_ptr.* += 1bumps the count through the pointer.counts.get("cow")returns?u32,nullfor a word that isn’t there.{?d}prints an optional number.
Step 4: Sort by count
Section titled “Step 4: Sort by count”A hash map keeps its entries in no useful order. To get “most common first”, copy the entries into a slice of small structs and sort that:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const text = try gpa.dupe(u8, "The cat sat on the mat. The dog sat on the log."); defer gpa.free(text);
var counts: std.StringHashMapUnmanaged(u32) = .empty; defer counts.deinit(gpa); _ = try countWords(gpa, &counts, text);
const sorted = try sortByCount(gpa, &counts); defer gpa.free(sorted);
for (sorted) |wc| { std.debug.print("{s:<5} {d}\n", .{ wc.word, wc.count }); }}
const WordCount = struct { word: []const u8, count: u32,};
/// Returns every word and its count, most common first. Caller frees the slice.fn sortByCount(gpa: std.mem.Allocator, counts: *const std.StringHashMapUnmanaged(u32)) ![]WordCount { const list = try gpa.alloc(WordCount, counts.count()); var it = counts.iterator(); var i: usize = 0; while (it.next()) |entry| : (i += 1) { list[i] = .{ .word = entry.key_ptr.*, .count = entry.value_ptr.* }; } std.mem.sort(WordCount, list, {}, moreCommonFirst); return list;}
fn moreCommonFirst(_: void, a: WordCount, b: WordCount) bool { if (a.count != b.count) return a.count > b.count; return std.mem.lessThan(u8, a.word, b.word); // ties: alphabetical}
/// Lowercases `text` in place, then counts every word in it./// The map's keys point into `text`, so `text` must outlive the map.fn countWords(gpa: std.mem.Allocator, counts: *std.StringHashMapUnmanaged(u32), text: []u8) !u32 { _ = std.ascii.lowerString(text, text);
var total: u32 = 0; var words: WordIterator = .{ .text = text }; while (words.next()) |word| { const entry = try counts.getOrPutValue(gpa, word, 0); entry.value_ptr.* += 1; total += 1; } return total;}
/// Splits text into words: runs of letters, digits and apostrophes.const WordIterator = struct { text: []const u8, pos: usize = 0,
fn next(self: *WordIterator) ?[]const u8 { while (true) { // Skip everything that can't be part of a word. while (self.pos < self.text.len and !isWordByte(self.text[self.pos])) self.pos += 1; if (self.pos == self.text.len) return null;
const start = self.pos; while (self.pos < self.text.len and isWordByte(self.text[self.pos])) self.pos += 1;
// 'quoted' -> quoted, but keep don't and it's. const word = std.mem.trim(u8, self.text[start..self.pos], "'"); if (word.len > 0) return word; } }};
fn isWordByte(c: u8) bool { // Bytes from 0x80 up are parts of non-ASCII UTF-8 letters like é or ü. return std.ascii.isAlphanumeric(c) or c == '\'' or c >= 0x80;}Output:
the 4on 2sat 2cat 1dog 1log 1mat 1- We know exactly how many entries there are,
counts.count(), sogpa.allocmakes a slice of that size in one go. No need for a growing ArrayList. counts.iterator()walks every entry.entry.key_ptr.*is the word andentry.value_ptr.*its count.std.mem.sortcallsmoreCommonFirst(a, b)and expectstruewhenabelongs beforeb. Higher count first; for equal counts, alphabetical withstd.mem.lessThan.
That tie-break isn’t just cosmetic. Without it, words with the same count could come out in a different order after you change the program, because the hash map’s order is arbitrary. With it, the same text always gives the same report, which makes the tool much easier to check.
Step 5: Read the file named on the command line
Section titled “Step 5: Read the file named on the command line”Now the outside world. The tool takes exactly one argument, the file name. Here’s that part on its own, printing just the file size:
const std = @import("std");
pub fn main(init: std.process.Init) !u8 { const io = init.io; const gpa = init.gpa;
const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len != 2) { std.debug.print("usage: wordcount <file>\n", .{}); return 2; } const path = args[1];
const text = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(64 * 1024 * 1024)) catch |err| { std.debug.print("can't read {s}: {t}\n", .{ path, err }); return 1; }; defer gpa.free(text);
std.debug.print("{s}: {d} bytes\n", .{ path, text.len }); return 0;}Try it with a good file, no file, a missing file and a folder:
zig run wordcount.zig -- story.txtzig run wordcount.zigzig run wordcount.zig -- nope.txtzig run wordcount.zig -- .You’ll see:
story.txt: 189 bytesusage: wordcount <file>can't read nope.txt: FileNotFoundcan't read .: IsDirThe new ideas:
mainreturns!u8. Theu8becomes the program’s exit code:0means success, anything else means failure. Scripts and shells check it (echo $?on Linux and macOS).2for “you used it wrong” and1for “something failed” is a common Unix habit.args[0]is the program itself, so one file name meansargs.len == 2. The--inzig run wordcount.zig -- story.txttellszig runthat the rest belongs to your program (Zig Command-Line Arguments).readFileAllocreads the whole file into memory..limited(64 * 1024 * 1024)refuses files of 64 MB or more, so a wrong path to some huge file fails cleanly instead of eating all your memory.catch |err| { ... }turns any read error into one clear line, and{t}prints the error’s name. For a tool that people run by hand, that’s friendlier than Zig’s default error trace. Messages go to stderr withstd.debug.print, so they don’t get mixed into the report if someone redirects the output to a file.
Step 6: The complete program
Section titled “Step 6: The complete program”Put everything together. main reads the arguments and the file, then calls the three helpers from Steps 2 to 4 and prints the top ten through a buffered stdout writer:
const std = @import("std");
/// How many of the most common words to show.const top_n = 10;
pub fn main(init: std.process.Init) !u8 { const io = init.io; const gpa = init.gpa;
var out_buffer: [4096]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(io, &out_buffer); const out = &stdout_writer.interface; defer out.flush() catch {};
// 1. Which file? const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len != 2) { std.debug.print("usage: wordcount <file>\n", .{}); return 2; } const path = args[1];
// 2. Read it. const text = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(64 * 1024 * 1024)) catch |err| { std.debug.print("can't read {s}: {t}\n", .{ path, err }); return 1; }; defer gpa.free(text);
// 3. Count. var counts: std.StringHashMapUnmanaged(u32) = .empty; defer counts.deinit(gpa); const total = try countWords(gpa, &counts, text);
// 4. Sort. const sorted = try sortByCount(gpa, &counts); defer gpa.free(sorted);
// 5. Report. try out.print("{s}: {d} words, {d} different\n\n", .{ path, total, counts.count() }); for (sorted[0..@min(top_n, sorted.len)], 1..) |wc, rank| { try out.print("{d:>3}. {s:<15} {d:>6}\n", .{ rank, wc.word, wc.count }); } return 0;}
const WordCount = struct { word: []const u8, count: u32,};
/// Lowercases `text` in place, then counts every word in it./// The map's keys point into `text`, so `text` must outlive the map.fn countWords(gpa: std.mem.Allocator, counts: *std.StringHashMapUnmanaged(u32), text: []u8) !u32 { _ = std.ascii.lowerString(text, text);
var total: u32 = 0; var words: WordIterator = .{ .text = text }; while (words.next()) |word| { const entry = try counts.getOrPutValue(gpa, word, 0); entry.value_ptr.* += 1; total += 1; } return total;}
/// Returns every word and its count, most common first. Caller frees the slice.fn sortByCount(gpa: std.mem.Allocator, counts: *const std.StringHashMapUnmanaged(u32)) ![]WordCount { const list = try gpa.alloc(WordCount, counts.count()); var it = counts.iterator(); var i: usize = 0; while (it.next()) |entry| : (i += 1) { list[i] = .{ .word = entry.key_ptr.*, .count = entry.value_ptr.* }; } std.mem.sort(WordCount, list, {}, moreCommonFirst); return list;}
fn moreCommonFirst(_: void, a: WordCount, b: WordCount) bool { if (a.count != b.count) return a.count > b.count; return std.mem.lessThan(u8, a.word, b.word); // ties: alphabetical}
/// Splits text into words: runs of letters, digits and apostrophes.const WordIterator = struct { text: []const u8, pos: usize = 0,
fn next(self: *WordIterator) ?[]const u8 { while (true) { // Skip everything that can't be part of a word. while (self.pos < self.text.len and !isWordByte(self.text[self.pos])) self.pos += 1; if (self.pos == self.text.len) return null;
const start = self.pos; while (self.pos < self.text.len and isWordByte(self.text[self.pos])) self.pos += 1;
// 'quoted' -> quoted, but keep don't and it's. const word = std.mem.trim(u8, self.text[start..self.pos], "'"); if (word.len > 0) return word; } }};
fn isWordByte(c: u8) bool { // Bytes from 0x80 up are parts of non-ASCII UTF-8 letters like é or ü. return std.ascii.isAlphanumeric(c) or c == '\'' or c >= 0x80;}Run it on the story:
zig run wordcount.zig -- story.txtYou’ll see the report from the top of the page. For a bigger test, build a fast version and let it count the words of its own source code:
zig build-exe wordcount.zig -O fast./wordcount wordcount.zigYou’ll see:
wordcount.zig: 503 words, 173 different
1. const 20 2. text 19 3. std 17 4. self 16 5. word 13 6. gpa 12 7. count 11 8. counts 11 9. pos 10 10. return 10A few things worth a second look in main:
- Every allocation has its
deferright below it: the file text, the map, the sorted slice. Whenmainreturns, they’re freed in reverse order. Run it in a debug build (plainzig run) andinit.gpawould print a leak report if you forgot one. defer out.flush() catch {};makes sure the report reaches the screen howevermainends.catch {}is needed because adefercan’t return an error.sorted[0..@min(top_n, sorted.len)]takes at most ten entries, and fewer if the file has fewer different words. Slicing past the end would be a panic.for (..., 1..) |wc, rank|loops over the slice and a counter starting at 1 together, which gives us the rank numbers.{s:<15}pads the word to 15 characters on the left and{d:>6}right-aligns the count, so the columns line up (Zig Format Strings).
Common mistakes
Section titled “Common mistakes”Freeing the text too early. It’s tempting to tidy up like this: read the file, count, then gpa.free(text) because “we’re done with the text”. We aren’t. The map’s keys and the word fields in sorted are slices into text, so after the free they point at memory that’s been given back. In a debug build you’d print garbage, and in other builds anything can happen. The fix is the order the program uses: defer gpa.free(text) right after reading, so the text lives until the end of main. If you really need the keys to outlive the text, copy each new key with gpa.dupe (and free them all later).
Counting The and the separately. Forget the lowerString line and the report has both, each with half the count. Normalise text before you count it.
Printing the hash map directly and expecting an order. Iterating a hash map gives you entries in whatever order its internal table happens to have. It isn’t insertion order and it isn’t sorted. If order matters, sort, as in Step 4, or use an ArrayHashMap, which remembers insertion order.
Forgetting the -- with zig run. zig run wordcount.zig story.txt makes Zig think story.txt is another input for the compiler, and it stops with error: unrecognized file extension of parameter "story.txt". Everything after -- goes to your program.
Ideas to extend it
Section titled “Ideas to extend it”- Read stdin when there’s no file. Make
wordcount < story.txtandcat *.txt | wordcountwork: ifargs.len == 1, read stdin instead.stdin_reader.interface.allocRemaining(gpa, .limited(...))reads everything into one buffer. - Choose how many to show.
wordcount story.txt 20shows the top 20. Parse the second argument withstd.fmt.parseInt. - Skip boring words. Leave out
the,a,and,to… Put them in astd.StaticStringMap(void)built at compile time and skip any word it contains. - Count lines and characters too, like the Unix
wccommand. Lines are the number of\nbytes. For characters (not bytes), look atstd.unicode.utf8CountCodepoints. - Several files. Accept any number of file names and count them all into one map. Watch out: the map’s keys point into each file’s text, so every file’s text has to stay alive until the end. An arena makes that easy.
- Write tests.
WordIteratorandcountWordsdon’t touch files, so a fewtestblocks with tricky strings (empty text, only punctuation,''') are quick to write. See Zig Testing.
- A Zig iterator is just a struct with a
nextmethod that returns?T;while (it.next()) |x|runs until it returnsnull. std.StringHashMapUnmanaged(u32)withgetOrPutValue(gpa, word, 0)counts things in one lookup per word.- A string map stores key slices, not copies: whatever the keys point into must outlive the map.
- To sort a map, copy its entries into a slice and call
std.mem.sortwith a compare function that uses strict>or<. A tie-breaker makes the output repeatable. maincan return!u8to set the exit code. Turn read errors into a one-line message on stderr.readFileAlloc(..., .limited(n))reads a whole file safely;defer gpa.free(text)right away.
Next up: Zig Project: To-Do List CLI, a command-line app with add, list, done and remove that saves your tasks to a file.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”std.hash_mapsource (0.17.1):StringHashMapUnmanaged,getOrPutValue,iteratorand the note that key memory is managed by the caller.std.mem.sortand friends (0.17.1 source): the stable block sort behindstd.mem.sort, plusasc,descand binary search.whilewith optionals in the 0.17.1 reference: the loop shape every iterator uses.std.asciisource (0.17.1):lowerString,isAlphanumericand the other ASCII helpers, and why they leave non-ASCII bytes alone.