typestar

std.mem in Zig

Strings are []const u8, and std.mem is the toolbox that works them.

const std = @import("std");

pub fn main() void {
    const motto = "measure twice, cut once";

    // Strings are []const u8; std.mem does the string work.
    const starts = std.mem.startsWith(u8, motto, "measure");
    std.debug.print("starts well? {}\n", .{starts});
    std.debug.print("'cut' at: {?d}\n", .{std.mem.indexOf(u8, motto, "cut")});
    std.debug.print("equal? {}\n", .{std.mem.eql(u8, motto[0..7], "measure")});

    var words = std.mem.tokenizeAny(u8, motto, " ,");
    while (words.next()) |w| std.debug.print("[{s}] ", .{w});
    std.debug.print("\n", .{});
}

How it works

  1. startsWith, indexOf, and eql cover the everyday questions.
  2. indexOf returns an optional — {?d} prints the maybe-index directly.
  3. tokenizeAny splits on spaces and commas without allocating anything.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
544
Tokens
187
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 173 seconds.

Type this snippet

Step 1 of 3 in The standard library, step 22 of 27 in Language basics.

← Previous Next →