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.memfunctions take the item type first:std.mem.eql(u8, a, b). For text, that’s alwaysu8.- 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.
Comparing
Section titled “Comparing”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: trueends with .pdf: falsesame ignoring case: trueapple vs banana: .ltpear < peach: falsestartsWithandendsWithare case-sensitive, so.PDFdoesn’t end with.pdf.std.ascii.eqlIgnoreCasetreatsAandaas equal. It only knows English letters (ASCII);Éandéare still different to it.std.mem.ordercompares like a dictionary and returns.lt(less than),.eqor.gt.std.mem.lessThangives abool, which is what you need for sorting a list of strings."pear"isn’t less than"peach"becausercomes aftera.
Searching with find
Section titled “Searching with find”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:
5null4122file name: slices.mdxfindsearches for a string,findScalarfor a single byte (note the'/'in single quotes), and theLastversions search from the end.{?}prints an optional: the number, ornull.counttells you how many times a piece appears.- In the
if,|i|is the index, andpath[i + 1 ..]slices off everything after the last/. Optionals get a full lesson in Zig Optionals.
Trimming
Section titled “Trimming”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.
Cutting a string in two
Section titled “Cutting a string in two”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: Adauser -> adaoption: verbosenot a pngcutScalarsplits at a single byte andcutat a string. Both give you two slices, which you unpack withconst key, const value = parts;.cutPrefixchecks that the text starts with something and gives you the rest.cutSuffixdoes the same at the end.elsehandles 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.
Splitting and tokenizing
Section titled “Splitting and tokenizing”To break text into many pieces, there are two families, and the difference between them matters:
splitreturns every piece, including empty ones between two separators in a row.tokenizeskips 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: one2: two3: threefirst: buildrest: test -> deploytokenizeAny 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 case and replacing
Section titled “Changing case and replacing”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 ZIGsnake-case-nameZig tutorialupperString(&buf, text)writes the uppercase version intobufand returns the filled part.lowerStringdoes 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), andreplaceScalarswaps one byte for another in place.toUpperandtoLowerwork on one byte. LikeeqlIgnoreCase, they only change English letters.
Building new text with an allocator
Section titled “Building new text with an allocator”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, blueI 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.
Turning text into numbers
Section titled “Turning text into numbers”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: 43ff is 255two of them: 19.98error.InvalidCharactererror.OverflowThe 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.
A word about Unicode
Section titled “A word about Unicode”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.
Practice
Section titled “Practice”1. Read a setting
Section titled “1. Read a setting”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 secondsWithout the trim, parseInt would see " 30 " and fail with InvalidCharacter.
2. Count the words
Section titled “2. Count the words”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: languagelongest 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.
3. Add up a CSV row
Section titled “3. Add up a CSV row”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 35With 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, passu8first) andstd.ascii(letters and digits). - Compare with
eql,startsWith,endsWith,std.ascii.eqlIgnoreCase, andlessThanororderfor sorting. - Search with
find,findScalarand theLastversions; they return?usize(old name:indexOf). trim,trimStart,trimEndstrip a set of bytes;cut,cutScalar,cutPrefixsplit in two.split*keeps empty pieces,tokenize*skips them. Both return an iterator: loop withwhile (it.next()) |piece|.- Most helpers return slices of your text; building new text (
join,replaceOwned) needs an allocator. std.fmt.parseIntandparseFloatturn text into numbers, and can fail.
Next up: Zig Structs, how to group related values into your own types.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig 0.16.0 release notes: mem cut functions and “find”: why
indexOfbecamefind, and the newcutfunctions. - Zig 0.17.0 release notes: the latest standard library changes.
- Zig standard library documentation: searchable docs for
std.mem,std.ascii,std.fmtandstd.unicode. - Zig language reference: Slices: the type all of these functions work on.