Zig Strings
Zig has no dedicated string type. A string is simply a sequence of bytes, usually encoded as UTF-8. By convention, functions that take text accept []const u8 — a read-only slice of bytes. Once you accept that, everything you learned about arrays and slices applies to text too.
String literals
const std = @import("std");
pub fn main() void {
const greeting = "Xin chào";
std.debug.print("{s}\n", .{greeting});
std.debug.print("type: {s}\n", .{@typeName(@TypeOf(greeting))});
std.debug.print("bytes: {d}\n", .{greeting.len});
std.debug.print("first byte: {c} ({d})\n", .{ greeting[0], greeting[0] });
}Xin chào
type: *const [9:0]u8
bytes: 9
first byte: X (88)
A literal's type is *const [N:0]u8: a pointer to a constant array of N bytes followed by a hidden zero byte (the :0 sentinel, handy for C interop). It converts automatically to []const u8. Notice .len is 9, not 8: the letter à takes two bytes in UTF-8. .len always counts bytes, not characters.
Escape sequences and multiline strings
| Escape | Meaning |
|---|---|
\n |
newline |
\t |
tab |
\\ |
backslash |
\" |
double quote |
\x41 |
byte with hex value 41 (A) |
\u{1F600} |
Unicode code point, encoded as UTF-8 |
For longer text, Zig has multiline string literals: every line starts with \\ and no escapes are processed inside.
const std = @import("std");
pub fn main() void {
const banner =
\\+--------+
\\| ZIG \n |
\\+--------+
;
std.debug.print("{s}\n", .{banner});
std.debug.print("tab:\there, quote: \"ok\"\n", .{});
}+--------+
| ZIG \n |
+--------+
tab: here, quote: "ok"
Comparing strings
== compares pointers, not contents, so it is not allowed on slices. Use std.mem.eql:
const std = @import("std");
pub fn main() void {
const input: []const u8 = "yes";
if (std.mem.eql(u8, input, "yes")) {
std.debug.print("confirmed\n", .{});
}
std.debug.print("starts with 'ye': {}\n", .{std.mem.startsWith(u8, input, "ye")});
std.debug.print("ends with 'no': {}\n", .{std.mem.endsWith(u8, input, "no")});
std.debug.print("order: {t}\n", .{std.mem.order(u8, "apple", "banana")});
}confirmed
starts with 'ye': true
ends with 'no': false
order: lt
Searching, splitting and trimming
| Function | Result |
|---|---|
std.mem.indexOf(u8, s, "ab") |
position of a substring, or null |
std.mem.count(u8, s, "ab") |
number of occurrences |
std.mem.trim(u8, s, " ") |
slice without leading/trailing spaces |
std.mem.tokenizeScalar(u8, s, ' ') |
iterator over words, skipping empty parts |
std.mem.splitScalar(u8, s, ',') |
iterator over fields, keeping empty parts |
std.mem.replaceOwned(…) |
new string with replacements (needs an allocator) |
const std = @import("std");
pub fn main() void {
const line = " red,green,,blue ";
const trimmed = std.mem.trim(u8, line, " ");
std.debug.print("trimmed: '{s}'\n", .{trimmed});
std.debug.print("'green' at {?d}\n", .{std.mem.indexOf(u8, trimmed, "green")});
var fields = std.mem.splitScalar(u8, trimmed, ',');
while (fields.next()) |f| std.debug.print("field: '{s}'\n", .{f});
var words = std.mem.tokenizeScalar(u8, " one two three ", ' ');
var n: usize = 0;
while (words.next()) |_| n += 1;
std.debug.print("{d} words\n", .{n});
}trimmed: 'red,green,,blue'
'green' at 4
field: 'red'
field: 'green'
field: ''
field: 'blue'
3 words
The returned pieces are slices pointing into the original text — no memory is allocated.
Building strings
Concatenating literals works at compile time with ++. For runtime values, format into a buffer with std.fmt.bufPrint, or allocate with std.fmt.allocPrint (see the Allocators lesson):
const std = @import("std");
pub fn main() !void {
const prefix = "user" ++ "-"; // compile time
var buf: [64]u8 = undefined;
const id: u32 = 1207;
const name = try std.fmt.bufPrint(&buf, "{s}{d:0>6}", .{ prefix, id });
std.debug.print("{s} ({d} bytes)\n", .{ name, name.len });
var upper: [32]u8 = undefined;
const shout = std.ascii.upperString(&upper, "quiet please");
std.debug.print("{s}\n", .{shout});
}user-001207 (11 bytes)
QUIET PLEASE
bufPrint returns an error if the buffer is too small, which is why it needs try (more about that in the Errors lesson).
Tip: For character tests on ASCII bytes use
std.ascii:isDigit,isAlphabetic,isWhitespace,toUpper,toLower. For real Unicode work, iterate code points withstd.unicode.Utf8View.
Test yourself
Which type is conventionally used for a read-only string parameter?
- String
- []const u8
- char*
- []u21
How do you check whether two strings have the same contents?
- a == b
- std.mem.eql(u8, a, b)
- a.equals(b)
- @strcmp(a, b)
What is "día".len?
- 3
- 4
- 2
- It does not compile