Zig, lesson 8
Zig has no special string type. A string is a slice of bytes, []const u8, and a string
literal like "hello" is a constant array of bytes that turns into a slice whenever you need one.
That makes strings simple and predictable, and the standard library supplies the tools.
Indexing gives you a u8, a single byte. A character literal in single quotes, like 'Z', is
just that byte's number, so word[0] == 'Z' is true. Plain English letters take one byte each;
letters like é take more, so len counts bytes, not visible characters. The exercises stick to
plain ASCII text.
2 exercises to try what you just read.
A for loop walks over the bytes:
std.mem works on any slice, including strings, and std.ascii works on single ASCII bytes:
| Call | Result |
|---|---|
std.mem.eql(u8, a, b) | true if the two strings have the same bytes |
std.mem.startsWith(u8, s, "He") | does s begin with "He"? |
std.mem.indexOf(u8, s, "lo") | position of "lo", or null |
std.mem.count(u8, "banana", "a") | 3 |
std.ascii.toUpper('q') | 'Q' |
std.ascii.isDigit(c) | is c one of '0' to '9'? |
A string literal is read-only. To build a changed version, you need memory to put it in, and in
Zig that means an allocator. With the arena from main:
allocPrint is like print, but it returns the text as a new string instead of writing it out.
For text known at compile time, ++ joins two literals: "Hello, " ++ "Zig".
The receipt below keeps three facts about each item. A struct bundles them, and can carry
functions that work on it:
The final exercise uses every lesson so far: the reader and writer, parsing numbers, a struct, an
ArrayList of items, loops that total things up, a decision for the empty receipt, and formatted
output. A good plan: read N; for each line, split it with std.mem.tokenizeScalar, dupe the
name (the line buffer is reused), and append an Item; then loop once to print and total, using
a strict > to remember the first biggest line.
Read one line of text and print three lines:
Vowels: N, where N counts the letters a e i o u in either case.Input: one line (ASCII letters, spaces and punctuation; it may be empty).
prints
A switch on std.ascii.toLower(c) with the prong 'a', 'e', 'i', 'o', 'u' => is a tidy way to
spot vowels.
Print a receipt for a shopping trip.
Input: the first line is the number of items N (0 or more). Each of the next N lines has an
item name (one word), a quantity and a unit price in whole euros, separated by spaces.
Output:
name xQTY = LINE_TOTAL,Items: and the sum of all quantities,Total: and the sum of all line totals,Biggest: and the name of the item with the largest line total (the first one if there is
a tie), or none if there are no items.prints
const word = "Zig";
// word.len is 3, word[0] is 'Z'var spaces: u32 = 0;
for (word) |c| {
if (c == ' ') spaces += 1;
}const shout = try std.ascii.allocUpperString(arena, "hey"); // "HEY"
const copy = try arena.dupe(u8, "abc"); // a mutable copy
std.mem.reverse(u8, copy); // now "cba"
const label = try std.fmt.allocPrint(arena, "{s}-{d}", .{ "row", 7 }); // "row-7"const Item = struct {
name: []const u8,
qty: u64,
price: u64,
fn lineTotal(self: Item) u64 {
return self.qty * self.price;
}
};
const apples = Item{ .name = "apple", .qty = 3, .price = 2 };
// apples.lineTotal() is 6Hello thereHELLO THERE
ereht olleH
Vowels: 43
apple 3 2
bread 1 4
cheese 2 5apple x3 = 6
bread x1 = 4
cheese x2 = 10
Items: 6
Total: 20
Biggest: cheese