Learn/Zig/8. Strings and a small project
Lesson 8 of 8
Sign in

Zig, lesson 8

Strings and a small project

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.

Bytes and characters

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.

Exercise 1

Shout, flip and count

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

A for loop walks over the bytes:

The string toolbox

std.mem works on any slice, including strings, and std.ascii works on single ASCII bytes:

CallResult
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'?

Changing text means new memory

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".

Grouping data with a struct

The receipt below keeps three facts about each item. A struct bundles them, and can carry functions that work on it:

Putting it all together

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.

Further reading

  • Zig Language Reference: String literals
  • Zig Language Reference: struct
  • Standard library: std.mem and std.ascii

Read one line of text and print three lines:

  1. the text in uppercase,
  2. the text reversed,
  3. 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:

  • one line per item, in input order: name xQTY = LINE_TOTAL,
  • then Items: and the sum of all quantities,
  • then Total: and the sum of all line totals,
  • then 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 6
Hello there
HELLO THERE
ereht olleH
Vowels: 4
3
apple 3 2
bread 1 4
cheese 2 5
apple x3 = 6
bread x1 = 4
cheese x2 = 10
Items: 6
Total: 20
Biggest: cheese