Skip to content

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.

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 2

What you’ll practise:

  • Writing a small iterator (a struct with a next method) that splits text into words (Zig Iterators).
  • Counting with std.StringHashMapUnmanaged and getOrPutValue (Zig HashMap).
  • Sorting with std.mem.sort and 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.

Make a folder with one source file, wordcount.zig, and the story to test with:

Terminal window
mkdir wordcount
cd wordcount
cat > 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.

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:

  • pos remembers where we are in the text between calls. It starts at 0 thanks to the default value = 0, so creating the iterator only needs .{ .text = text }.
  • The first inner while skips over separators. If that reaches the end, there are no more words, so next returns null, which ends the while (words.next()) |word| loop in main. The reference calls that loop shape a while with optionals.
  • The second inner while walks 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' gives au, not 'au. If a “word” was only apostrophes, it’s empty after trimming, and the outer while (true) goes round again to find the next one.

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:

  1. The and the should count as the same word, so we lowercase the text first.
  2. 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_map source 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 different
the: 4
sat: 2
cow: null

Piece by piece:

  • gpa.dupe(u8, "...") copies the string literal into memory we own. A string literal is read-only, and countWords wants to change the text, so it takes []u8 (changeable bytes). Passing the literal directly wouldn’t compile. In the real program the text comes from readFileAlloc, which already gives us a []u8.
  • std.ascii.lowerString(text, text) writes the lowercase version of text into text itself, 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 value 0 if the word is new. Then entry.value_ptr.* += 1 bumps the count through the pointer.
  • counts.get("cow") returns ?u32, null for a word that isn’t there. {?d} prints an optional number.

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 4
on 2
sat 2
cat 1
dog 1
log 1
mat 1
  • We know exactly how many entries there are, counts.count(), so gpa.alloc makes 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 and entry.value_ptr.* its count.
  • std.mem.sort calls moreCommonFirst(a, b) and expects true when a belongs before b. Higher count first; for equal counts, alphabetical with std.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:

Terminal window
zig run wordcount.zig -- story.txt
zig run wordcount.zig
zig run wordcount.zig -- nope.txt
zig run wordcount.zig -- .

You’ll see:

story.txt: 189 bytes
usage: wordcount <file>
can't read nope.txt: FileNotFound
can't read .: IsDir

The new ideas:

  • main returns !u8. The u8 becomes the program’s exit code: 0 means success, anything else means failure. Scripts and shells check it (echo $? on Linux and macOS). 2 for “you used it wrong” and 1 for “something failed” is a common Unix habit.
  • args[0] is the program itself, so one file name means args.len == 2. The -- in zig run wordcount.zig -- story.txt tells zig run that the rest belongs to your program (Zig Command-Line Arguments).
  • readFileAlloc reads 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 with std.debug.print, so they don’t get mixed into the report if someone redirects the output to a file.

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:

Terminal window
zig run wordcount.zig -- story.txt

You’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:

Terminal window
zig build-exe wordcount.zig -O fast
./wordcount wordcount.zig

You’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 10

A few things worth a second look in main:

  • Every allocation has its defer right below it: the file text, the map, the sorted slice. When main returns, they’re freed in reverse order. Run it in a debug build (plain zig run) and init.gpa would print a leak report if you forgot one.
  • defer out.flush() catch {}; makes sure the report reaches the screen however main ends. catch {} is needed because a defer can’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).

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.

  • Read stdin when there’s no file. Make wordcount < story.txt and cat *.txt | wordcount work: if args.len == 1, read stdin instead. stdin_reader.interface.allocRemaining(gpa, .limited(...)) reads everything into one buffer.
  • Choose how many to show. wordcount story.txt 20 shows the top 20. Parse the second argument with std.fmt.parseInt.
  • Skip boring words. Leave out the, a, and, to… Put them in a std.StaticStringMap(void) built at compile time and skip any word it contains.
  • Count lines and characters too, like the Unix wc command. Lines are the number of \n bytes. For characters (not bytes), look at std.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. WordIterator and countWords don’t touch files, so a few test blocks with tricky strings (empty text, only punctuation, ''') are quick to write. See Zig Testing.
  • A Zig iterator is just a struct with a next method that returns ?T; while (it.next()) |x| runs until it returns null.
  • std.StringHashMapUnmanaged(u32) with getOrPutValue(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.sort with a compare function that uses strict > or <. A tie-breaker makes the output repeatable.
  • main can return !u8 to 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

1. Why does the program call std.ascii.lowerString(text, text) before counting?
2. The keys in counts are slices into text. What happens if you free text before printing the report?
3. What should a compare function for std.mem.sort return when both items are equal?
4. Why does main return !u8 in this program?