Zig String Operations
String operations are tasks such as comparing, checking the start of, and trimming text. Helper functions in the std.mem part of the standard library do these tasks.
eql matches equal text only
The helper compares the two strings byte by byte. The same text gives true and different text gives false.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const a: []const u8 = "zig";
const b: []const u8 = "zig";
const c: []const u8 = "zag";
try out.print("{}\n", .{std.mem.eql(u8, a, b)});
try out.print("{}\n", .{std.mem.eql(u8, a, c)});
}
startsWith checks the opening bytes
The phrase begins with hello and does not begin with world. The two results prove both checks.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const phrase: []const u8 = "hello world";
try out.print("{}\n", .{std.mem.startsWith(u8, phrase, "hello")});
try out.print("{}\n", .{std.mem.startsWith(u8, phrase, "world")});
}
trim removes spaces from both ends
The messy string carries two spaces on each side. Trim removes them and leaves three bytes.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const messy: []const u8 = " zig ";
const clean = std.mem.trim(u8, messy, " ");
try out.print("{s}\n", .{clean});
try out.print("{d}\n", .{clean.len});
}
Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const saved: []const u8 = " open ";
const clean = std.mem.trim(u8, saved, " ");
try out.print("{s}\n", .{clean});
try out.print("{d}\n", .{clean.len});
try out.print("{}\n", .{std.mem.eql(u8, clean, "open")});
try out.print("{}\n", .{std.mem.startsWith(u8, clean, "op")});
}
Key points
- std.mem: the mem part of the standard library holds the string helper functions.
- eql: std.mem.eql compares two strings byte by byte and returns true when they match.
- startsWith: std.mem.startsWith reports whether a string begins with a given prefix.
- trim: std.mem.trim returns a slice with chosen characters removed from both ends.
- Result type: eql and startsWith return a bool, so a result fits in an if condition.
In this example, trim first removes the spaces around the saved word. The cleaned word prints as open with length 4. eql then confirms it matches open, and startsWith confirms it begins with op.
Note
== is a compile error on slices, so string comparison always goes through a helper such as eql.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which helper removes spaces from both ends of a string?