Skip to content

Zig Strings in Depth

In Zig Strings you learned that a string is just a slice of bytes, []const u8, with no methods of its own. So where are trim, split and indexOf? They live in the standard library as plain functions, mostly in std.mem (which works on slices of anything) and std.ascii (for letters and digits). This lesson is a tour of the ones you’ll use every week, with the 0.17 names. Keep it open the first few times you process text.

Two things are true for almost all of them, and knowing them makes the whole toolbox easier:

  • std.mem functions take the item type first: std.mem.eql(u8, a, b). For text, that’s always u8.
  • They don’t copy. Search functions return an index, and trim, cut and split return slices of your original text. Only the few functions that build new text take an allocator.

You already know std.mem.eql. Its friends check the start, the end, and comparisons that ignore case:

const std = @import("std");
pub fn main() void {
const file = "report-2026.PDF";
std.debug.print("starts with report: {}\n", .{std.mem.startsWith(u8, file, "report")});
std.debug.print("ends with .pdf: {}\n", .{std.mem.endsWith(u8, file, ".pdf")});
std.debug.print("same ignoring case: {}\n", .{std.ascii.eqlIgnoreCase(file, "REPORT-2026.pdf")});
std.debug.print("apple vs banana: {}\n", .{std.mem.order(u8, "apple", "banana")});
std.debug.print("pear < peach: {}\n", .{std.mem.lessThan(u8, "pear", "peach")});
}

Output:

starts with report: true
ends with .pdf: false
same ignoring case: true
apple vs banana: .lt
pear < peach: false
  • startsWith and endsWith are case-sensitive, so .PDF doesn’t end with .pdf.
  • std.ascii.eqlIgnoreCase treats A and a as equal. It only knows English letters (ASCII); É and é are still different to it.
  • std.mem.order compares like a dictionary and returns .lt (less than), .eq or .gt. std.mem.lessThan gives a bool, which is what you need for sorting a list of strings. "pear" isn’t less than "peach" because r comes after a.

std.mem.find looks for a piece of text and gives you the index where it starts. When it isn’t there, you get null, so the result type is ?usize, an optional. The easiest way to use one is if (...) |index|, which runs only when something was found:

const std = @import("std");
pub fn main() void {
const path = "docs/lessons/slices.mdx";
std.debug.print("{?}\n", .{std.mem.find(u8, path, "lessons")});
std.debug.print("{?}\n", .{std.mem.find(u8, path, "rust")});
std.debug.print("{?}\n", .{std.mem.findScalar(u8, path, '/')});
std.debug.print("{?}\n", .{std.mem.findScalarLast(u8, path, '/')});
std.debug.print("{d}\n", .{std.mem.count(u8, "banana", "an")});
if (std.mem.findScalarLast(u8, path, '/')) |i| {
std.debug.print("file name: {s}\n", .{path[i + 1 ..]});
}
}

Output:

5
null
4
12
2
file name: slices.mdx
  • find searches for a string, findScalar for a single byte (note the '/' in single quotes), and the Last versions search from the end.
  • {?} prints an optional: the number, or null.
  • count tells you how many times a piece appears.
  • In the if, |i| is the index, and path[i + 1 ..] slices off everything after the last /. Optionals get a full lesson in Zig Optionals.

User input and file lines often come with spaces or a newline at the ends. std.mem.trim removes them. Its last argument is the set of bytes to strip, not a word:

const std = @import("std");
pub fn main() void {
const line = " hello world \n";
std.debug.print("[{s}]\n", .{std.mem.trim(u8, line, " \n")});
std.debug.print("[{s}]\n", .{std.mem.trimStart(u8, line, " ")});
std.debug.print("[{s}]\n", .{std.mem.trimEnd(u8, line, " \n")});
std.debug.print("[{s}]\n", .{std.mem.trim(u8, "--==title==--", "-=")});
}

Output:

[hello world]
[hello world
]
[ hello world]
[title]

The brackets in the output show exactly where each result starts and ends. trimStart only strips the front and trimEnd only the back. The space in the middle of hello world is never touched: trimming stops at the first byte that isn’t in the set. For “any whitespace”, pass " \t\r\n"; Windows files end their lines with \r\n, and forgetting the \r is a classic.

Very often you want “the part before X and the part after X”: a key=value setting, a name: value header, a --flag. The cut functions do exactly that, and return null when the separator isn’t there:

const std = @import("std");
pub fn main() void {
if (std.mem.cutScalar(u8, "name=Ada", '=')) |parts| {
const key, const value = parts;
std.debug.print("key: {s}, value: {s}\n", .{ key, value });
}
if (std.mem.cut(u8, "user: ada", ": ")) |parts| {
const label, const rest = parts;
std.debug.print("{s} -> {s}\n", .{ label, rest });
}
const flag = "--verbose";
if (std.mem.cutPrefix(u8, flag, "--")) |name| {
std.debug.print("option: {s}\n", .{name});
}
if (std.mem.cutSuffix(u8, "photo.jpg", ".png")) |base| {
std.debug.print("png: {s}\n", .{base});
} else {
std.debug.print("not a png\n", .{});
}
}

Output:

key: name, value: Ada
user -> ada
option: verbose
not a png
  • cutScalar splits at a single byte and cut at a string. Both give you two slices, which you unpack with const key, const value = parts;.
  • cutPrefix checks that the text starts with something and gives you the rest. cutSuffix does the same at the end.
  • else handles the “not found” case.

These were added in Zig 0.16, so you won’t find them in older tutorials. They replace a lot of find plus slicing by hand.

To break text into many pieces, there are two families, and the difference between them matters:

  • split returns every piece, including empty ones between two separators in a row.
  • tokenize skips empty pieces, so several separators in a row count as one.
const std = @import("std");
pub fn main() void {
const csv = "red,,green,blue";
var parts = std.mem.splitScalar(u8, csv, ',');
while (parts.next()) |part| {
std.debug.print("split: [{s}]\n", .{part});
}
var tokens = std.mem.tokenizeScalar(u8, csv, ',');
while (tokens.next()) |token| {
std.debug.print("tokenize: [{s}]\n", .{token});
}
}

Output:

split: [red]
split: []
split: [green]
split: [blue]
tokenize: [red]
tokenize: [green]
tokenize: [blue]

Neither one builds a list. They return an iterator: a small value you call .next() on, which gives you the next piece, or null when there are no more. while (parts.next()) |part| is the loop you’ll write every time. Because the iterator changes as you go, it has to be a var.

Use split when empty fields mean something, like an empty cell in a CSV file. Use tokenize for words separated by spaces, where two spaces shouldn’t produce an empty word. Each comes in three flavours:

Function Separator
splitScalar / tokenizeScalar one byte, like ','
splitSequence / tokenizeSequence a whole string, like " -> "
splitAny / tokenizeAny any byte from a set, like " \t\n"
const std = @import("std");
pub fn main() void {
var words = std.mem.tokenizeAny(u8, " one two\tthree\n", " \t\n");
var count: usize = 0;
while (words.next()) |word| {
count += 1;
std.debug.print("{d}: {s}\n", .{ count, word });
}
var steps = std.mem.splitSequence(u8, "build -> test -> deploy", " -> ");
std.debug.print("first: {s}\n", .{steps.first()});
std.debug.print("rest: {s}\n", .{steps.rest()});
}

Output:

1: one
2: two
3: three
first: build
rest: test -> deploy

tokenizeAny with spaces, tabs and newlines is the usual “split into words”. On a split iterator, .first() gives the first piece (there’s always at least one), and .rest() gives everything that hasn’t been read yet, without splitting it.

Changing text means writing bytes, so you need a place to write them: a var array, or a buffer. The std.ascii helpers work on single bytes or fill a buffer you give them:

const std = @import("std");
pub fn main() void {
var buf: [64]u8 = undefined;
const loud = std.ascii.upperString(&buf, "hello zig");
std.debug.print("{s}\n", .{loud});
var name = "snake_case_name".*;
std.mem.replaceScalar(u8, &name, '_', '-');
std.debug.print("{s}\n", .{name});
var title = "zig tutorial".*;
title[0] = std.ascii.toUpper(title[0]);
std.debug.print("{s}\n", .{title});
}

Output:

HELLO ZIG
snake-case-name
Zig tutorial
  • upperString(&buf, text) writes the uppercase version into buf and returns the filled part. lowerString does the opposite. The buffer must be at least as long as the text.
  • "snake_case_name".* copies the literal into an array you own (literals themselves can’t change), and replaceScalar swaps one byte for another in place.
  • toUpper and toLower work on one byte. Like eqlIgnoreCase, they only change English letters.

Joining pieces or replacing a word with a longer one makes text of a new length, so these functions need an allocator to get memory, and you free it when you’re done:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const joined = try std.mem.join(gpa, ", ", &.{ "red", "green", "blue" });
defer gpa.free(joined);
std.debug.print("{s}\n", .{joined});
const replaced = try std.mem.replaceOwned(u8, gpa, "I like tea. Tea is nice, tea!", "tea", "coffee");
defer gpa.free(replaced);
std.debug.print("{s}\n", .{replaced});
}

Output:

red, green, blue
I like coffee. Tea is nice, coffee!

init.gpa is the allocator Zig passes to main, and try passes on the out-of-memory error if there is one. Every allocation gets a defer gpa.free(...) right below it, as you learned in Zig Defer. Notice Tea stayed: replaceOwned matches exact bytes, so it’s case-sensitive. Allocators are explained properly in Zig Allocators.

Text from a file or the user often holds numbers. std.fmt.parseInt takes the type you want, the text, and the base (10 for normal numbers, 16 for hex). Since the text might not be a number, it can fail, so you use try:

const std = @import("std");
pub fn main() !void {
const age = try std.fmt.parseInt(u8, "42", 10);
std.debug.print("next year: {d}\n", .{age + 1});
const hex = try std.fmt.parseInt(u32, "ff", 16);
std.debug.print("ff is {d}\n", .{hex});
const price = try std.fmt.parseFloat(f64, "9.99");
std.debug.print("two of them: {d}\n", .{price * 2});
const bad = std.fmt.parseInt(u8, "4x2", 10);
std.debug.print("{any}\n", .{bad});
const too_big = std.fmt.parseInt(u8, "300", 10);
std.debug.print("{any}\n", .{too_big});
}

Output:

next year: 43
ff is 255
two of them: 19.98
error.InvalidCharacter
error.Overflow

The last two show the errors you’ll get: InvalidCharacter when the text isn’t a number, and Overflow when it doesn’t fit the type (300 is too big for a u8). Parsing doesn’t trim for you, so "42\n" fails too: trim first. How to handle these errors nicely is the topic of Zig Errors.

Everything above works on bytes. That’s fine for searching and splitting, even with non-English text, because UTF-8 never confuses an ASCII byte like , or / with part of another character. But counting letters isn’t the same as counting bytes:

const std = @import("std");
pub fn main() !void {
const word = "héllo";
const view = try std.unicode.Utf8View.init(word);
var it = view.iterator();
var letters: usize = 0;
while (it.nextCodepoint()) |_| letters += 1;
std.debug.print("{d} bytes, {d} code points\n", .{ word.len, letters });
}

Output:

6 bytes, 5 code points

é takes two bytes. std.unicode.Utf8View checks that the text is valid UTF-8 and lets you walk it one code point at a time. Even code points aren’t always what a reader calls a “letter” (some emoji are several code points), and the standard library doesn’t try to handle that. For case-insensitive work with non-English text, you’ll need a third-party package.

Given const line = " timeout = 30 ";, get the key and the value without the spaces around them, and parse the value as a u32. Print timeout is 30 seconds.

Hint: cutScalar at '=', then trim each half with " ", then parseInt.

Show solution
const std = @import("std");
pub fn main() !void {
const line = " timeout = 30 ";
if (std.mem.cutScalar(u8, line, '=')) |parts| {
const raw_key, const raw_value = parts;
const key = std.mem.trim(u8, raw_key, " ");
const value = try std.fmt.parseInt(u32, std.mem.trim(u8, raw_value, " "), 10);
std.debug.print("{s} is {d} seconds\n", .{ key, value });
} else {
std.debug.print("no '=' in the line\n", .{});
}
}

Output:

timeout is 30 seconds

Without the trim, parseInt would see " 30 " and fail with InvalidCharacter.

Count the words in "Zig is a\tsmall language\n" and print the longest one.

Hint: tokenizeAny with " \t\n". Keep a longest slice and replace it when a word’s .len is bigger.

Show solution
const std = @import("std");
pub fn main() void {
const text = "Zig is a\tsmall language\n";
var words = std.mem.tokenizeAny(u8, text, " \t\n");
var count: usize = 0;
var longest: []const u8 = "";
while (words.next()) |word| {
count += 1;
if (word.len > longest.len) longest = word;
}
std.debug.print("{d} words, longest: {s}\n", .{ count, longest });
}

Output:

5 words, longest: language

longest is a slice into text, so keeping it costs nothing: no copy is made. The double space after Zig doesn’t create an empty word, because tokenize skips empty pieces.

Add up the numbers in "10,20,,5", treating the empty field as 0 and counting how many fields there are.

Hint: use splitScalar (not tokenize), because the empty field counts. Check field.len == 0 before parsing.

Show solution
const std = @import("std");
pub fn main() !void {
var fields = std.mem.splitScalar(u8, "10,20,,5", ',');
var total: u32 = 0;
var count: usize = 0;
while (fields.next()) |field| {
count += 1;
if (field.len == 0) continue;
total += try std.fmt.parseInt(u32, field, 10);
}
std.debug.print("{d} fields, total {d}\n", .{ count, total });
}

Output:

4 fields, total 35

With tokenizeScalar, you’d get 3 fields, which is wrong for a CSV row where position matters.

  • Text helpers are plain functions in std.mem (any slice, pass u8 first) and std.ascii (letters and digits).
  • Compare with eql, startsWith, endsWith, std.ascii.eqlIgnoreCase, and lessThan or order for sorting.
  • Search with find, findScalar and the Last versions; they return ?usize (old name: indexOf).
  • trim, trimStart, trimEnd strip a set of bytes; cut, cutScalar, cutPrefix split in two.
  • split* keeps empty pieces, tokenize* skips them. Both return an iterator: loop with while (it.next()) |piece|.
  • Most helpers return slices of your text; building new text (join, replaceOwned) needs an allocator.
  • std.fmt.parseInt and parseFloat turn text into numbers, and can fail.

Next up: Zig Structs, how to group related values into your own types.

Quick check

1. What does std.mem.find(u8, "hello", "xyz") return?
2. You split "a,,b" on ','. How many pieces do splitScalar and tokenizeScalar give?
3. What does the last argument of std.mem.trim(u8, text, " \n") mean?
4. Which of these needs an allocator?