Library reference

Find text inside a string

Look for a piece of text anywhere in a longer string. These examples match the letters exactly.

std.mem.indexOf

Simple example

Does abc contain b?

Start'abc' · 'b'
Resulttrue
lesson.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("{any}\n", .{std.mem.indexOf(u8, "abc", "b") != null});
}
Output
true
Advertisements

Everyday examples

Does a ticket marked blue-zone include the word blue?

Start'blue-zone' · 'blue'
Resulttrue
lesson.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("{any}\n", .{std.mem.indexOf(u8, "blue-zone", "blue") != null});
}
Output
true

Does a shelf marked fruit contain the word milk?

Start'fruit' · 'milk'
Resultfalse
lesson.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("{any}\n", .{std.mem.indexOf(u8, "fruit", "milk") != null});
}
Output
false

Does the route name East Road include Road?

Start'East Road' · 'Road'
Resulttrue
lesson.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("{any}\n", .{std.mem.indexOf(u8, "East Road", "Road") != null});
}
Output
true
Run the example
Terminal
zig run lesson.zig
Official documentation