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
startsWith,indexOf, andeqlcover the everyday questions.indexOfreturns an optional —{?d}prints the maybe-index directly.tokenizeAnysplits on spaces and commas without allocating anything.
Keywords and builtins used here
constfnpubu8varvoidwhile
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.
Step 1 of 3 in The standard library, step 22 of 27 in Language basics.