(This is referring to zig 0.14.0.)
To find the location of a subslice in a slice, either
std.mem.indexOf
or std.mem.indexOfPos
can be
used. If you want to start the search from a subslice of the original
slice (e.g. find the first “a” in a string starting at the 5th
character), you can either use indexOf
with a subslice as
the haystack (internally what std.mem
calls the slice to
search in), or use indexOfPos
with the
start_index
. They return different things:
const std = @import("std");
pub fn main() !void {
std.debug.print("{any}\n", .{std.mem.indexOf(u8, "abcdef", "d")});
std.debug.print("{any}\n", .{std.mem.indexOfPos(u8, "abcdef", 2, "d")});
std.debug.print("{any}\n", .{std.mem.indexOf(u8, "abcdef"[2..], "d")});
}
will yield
3
3
1
In hindsight this is obvious - if the haystack is a subslice, then the returned index is relative to that subslice.
Home | Back to blogThis work is licensed under
CC BY-NC 4.0