Skip to content

Zig Strings

Almost every program handles text: names, messages, file contents, commands. In Python or JavaScript a string is its own special type with lots of built-in methods. Zig keeps it simpler and more honest: a string is just a list of bytes. There’s no String type at all. That takes a little getting used to, but once it clicks, a lot of Zig makes sense, and you always know exactly what’s in memory.

The type you’ll write for text is []const u8. Read it from left to right: [] is a slice (a view of several items in a row), const means you won’t change them, and u8 means each item is a byte.

const std = @import("std");
pub fn main() void {
const greeting: []const u8 = "Hello";
std.debug.print("{s}\n", .{greeting});
std.debug.print("length: {d}\n", .{greeting.len});
std.debug.print("first byte: {c} ({d})\n", .{ greeting[0], greeting[0] });
}

Output:

Hello
length: 5
first byte: H (72)
  • {s} prints the bytes as text. If you forget the s and write {}, the build fails with cannot format slice without a specifier.
  • .len is the number of bytes.
  • greeting[0] is the first byte, a u8. {c} prints it as a character and {d} as its number ('H' is 72).

You’ll use []const u8 as the type of function parameters, struct fields and anything else that holds text. Slices get a full lesson in Zig Slices.

Text in double quotes in your source code is a string literal. Its type is a bit more detailed than []const u8:

const std = @import("std");
pub fn main() void {
const name = "Zig";
std.debug.print("{}\n", .{@TypeOf(name)});
}

Output:

*const [3:0]u8

That reads as “a pointer (*) to a constant array of 3 bytes, followed by a zero byte (:0)”. The extra zero byte at the end is there so the text can be handed straight to C functions, which find the end of a string by looking for a zero. The reference section on string literals has the exact rules.

You rarely need to write this type yourself. A string literal turns into a []const u8 automatically whenever one is expected, like in const greeting: []const u8 = "Hello"; above. The zero byte isn’t counted in .len. You’ll learn more about it in Zig Sentinel-Terminated Types.

Double quotes make a string. Single quotes make one character, which is just a number:

const std = @import("std");
pub fn main() void {
const letter: u8 = 'A';
const word: []const u8 = "A";
std.debug.print("{c} is the number {d}\n", .{ letter, letter });
std.debug.print("{s} is a string of {d} byte\n", .{ word, word.len });
}

Output:

A is the number 65
A is a string of 1 byte

Mixing them up is a common first mistake. const initial: u8 = "A"; fails with expected type 'u8', found '*const [1:0]u8': you gave it a string where a single byte was expected. Swap the double quotes for single quotes.

Inside a string, a backslash starts a special character:

const std = @import("std");
pub fn main() void {
std.debug.print("Line one\nLine two\n", .{});
std.debug.print("Name:\tAda\n", .{});
std.debug.print("She said \"hi\"\n", .{});
std.debug.print("A path: C:\\Users\\ada\n", .{});
std.debug.print("A smiley: \u{1F600}\n", .{});
}

Output:

Line one
Line two
Name: Ada
She said "hi"
A path: C:\Users\ada
A smiley: 😀

\n is a new line, \t a tab, \" a double quote and \\ a backslash. \u{1F600} puts in a Unicode character by its code (here, the smiley face), and \x41 puts in one byte by its hex value. The full list is in the reference under escape sequences.

For longer text, start each line with \\. Everything after the \\ up to the end of the line is part of the string, and lines are joined with a newline:

const std = @import("std");
pub fn main() void {
const help =
\\Usage: todo [command]
\\
\\Commands:
\\ add "task" Add a task
\\ list Show all tasks
;
std.debug.print("{s}\n", .{help});
}

Output:

Usage: todo [command]
Commands:
add "task" Add a task
list Show all tasks

There are no escapes in multiline strings, so " and \ are just themselves. That makes them great for help text, templates and test data. The string doesn’t end with a newline, which is why the print adds one. Note the ; on its own line: it ends the const statement.

Strings can’t be changed (but copies can)

Section titled “Strings can’t be changed (but copies can)”

A string literal is baked into your program and is read-only. Trying to change one is an error:

const std = @import("std");
pub fn main() void {
const word = "hello";
word[0] = 'H';
std.debug.print("{s}\n", .{word});
}
main.zig:5:9: error: cannot assign to constant
word[0] = 'H';
~~~~^~~

If you need text you can edit, copy it into an array you own. .* follows the pointer and gives you the array itself, and var makes your copy changeable:

const std = @import("std");
pub fn main() void {
var word = "hello".*;
word[0] = 'H';
std.debug.print("{s}\n", .{&word});
}

Output:

Hello

word is now a [5:0]u8, an array of 5 bytes on the stack. &word gives a pointer to it, which {s} can print. Text that grows or comes from a file needs memory you allocate, which is a later topic (Zig Memory).

Zig source files are UTF-8, so a string can hold any language and any emoji. But UTF-8 uses more than one byte for most characters outside plain English letters. And .len counts bytes:

const std = @import("std");
pub fn main() !void {
const word = "café";
std.debug.print("bytes: {d}\n", .{word.len});
std.debug.print("characters: {d}\n", .{try std.unicode.utf8CountCodepoints(word)});
for (word) |byte| {
std.debug.print("{x} ", .{byte});
}
std.debug.print("\n", .{});
}

Output:

bytes: 5
characters: 4
63 61 66 c3 a9

"café" is 4 characters but 5 bytes, because é is stored as two bytes, c3 a9. std.unicode.utf8CountCodepoints counts real characters (Unicode code points). It can fail if the bytes aren’t valid UTF-8, so it’s called with try, and main returns !void to allow that. Both are explained in Zig Try & Catch; for now, read try as “if this fails, stop and report the error”. The for loop goes over the string one byte at a time; loops are coming up in Zig For.

This is the same as in C, Go and Rust. Python and JavaScript hide it behind their string types, which is friendlier but costs memory and speed.

You can’t compare two strings with ==:

const std = @import("std");
pub fn main() void {
const a: []const u8 = "zig";
const b: []const u8 = "zig";
std.debug.print("{}\n", .{a == b});
}
main.zig:6:33: error: operator == not allowed for type '[]const u8'
std.debug.print("{}\n", .{a == b});
~~^~~~

A slice is a pointer plus a length, so == would only tell you whether two slices point at the same memory, not whether the text matches. That’s a classic C bug, and Zig refuses to guess. Use std.mem.eql, which compares the bytes one by one:

const std = @import("std");
pub fn main() void {
const command: []const u8 = "quit";
std.debug.print("is quit: {}\n", .{std.mem.eql(u8, command, "quit")});
std.debug.print("is help: {}\n", .{std.mem.eql(u8, command, "help")});
std.debug.print("starts with q: {}\n", .{std.mem.startsWith(u8, command, "q")});
}

Output:

is quit: true
is help: false
starts with q: true

The first argument, u8, says what kind of items you’re comparing. std.mem has many more helpers for searching, splitting and trimming, covered in Zig Strings in Depth.

You can take part of a string with [start..end]. The start is included, the end isn’t:

const std = @import("std");
pub fn main() void {
const date = "2026-11-26";
const year = date[0..4];
const month = date[5..7];
std.debug.print("year {s}, month {s}\n", .{ year, month });
const full = "Hello, " ++ "world!";
std.debug.print("{s}\n", .{full});
}

Output:

year 2026, month 11
Hello, world!

Slicing doesn’t copy anything. year is a view of the first four bytes of date.

++ joins two strings, but only when both are known at compile time, like two literals. For text that only exists while the program runs, like a name the user typed, ++ gives slice being concatenated must be comptime-known. Then you build the text into a buffer instead:

const std = @import("std");
pub fn main() !void {
var name: []const u8 = "Ada";
name = "Grace"; // pretend this came from the user
var buf: [64]u8 = undefined;
const message = try std.mem.print(&buf, "Hello, {s}!", .{name});
std.debug.print("{s} ({d} bytes)\n", .{ message, message.len });
}

Output:

Hello, Grace! (13 bytes)

std.mem.print works like print, but writes into buf and gives you back a slice of the part it filled. If the text doesn’t fit in the 64 bytes, it returns an error, which try passes on. When you don’t know the size in advance, an allocator’s print method makes room for you instead (Zig Allocators). Older code uses std.fmt.bufPrint and std.fmt.allocPrint for the same jobs: they still work in 0.17.1, but they’re deprecated.

Given const first: []const u8 = "Grace"; and const last: []const u8 = "Hopper";, print Initials: G.H..

Hint: first[0] is the first byte. Print it with {c}.

Show solution
const std = @import("std");
pub fn main() void {
const first: []const u8 = "Grace";
const last: []const u8 = "Hopper";
std.debug.print("Initials: {c}.{c}.\n", .{ first[0], last[0] });
}

Output:

Initials: G.H.

Indexing a string gives a u8, and {c} prints a byte as a character. This works because both names are plain ASCII.

Print access granted if const input: []const u8 = "open sesame"; equals the secret "open sesame", otherwise access denied.

Hint: == won’t build on slices. Use std.mem.eql(u8, a, b) inside an if.

Show solution
const std = @import("std");
pub fn main() void {
const secret = "open sesame";
const input: []const u8 = "open sesame";
if (std.mem.eql(u8, input, secret)) {
std.debug.print("access granted\n", .{});
} else {
std.debug.print("access denied\n", .{});
}
}

Output:

access granted

std.mem.eql returns true only when both slices have the same length and the same bytes.

Print the byte length and the character count of "Zürich". Expected output: Zürich: 7 bytes, 6 characters.

Hint: .len for bytes, std.unicode.utf8CountCodepoints for characters. It needs try, so main returns !void.

Show solution
const std = @import("std");
pub fn main() !void {
const city = "Zürich";
const chars = try std.unicode.utf8CountCodepoints(city);
std.debug.print("{s}: {d} bytes, {d} characters\n", .{ city, city.len, chars });
}

Output:

Zürich: 7 bytes, 6 characters

ü takes two bytes in UTF-8, so the byte count is one higher than the character count.

  • A string is a slice of bytes, []const u8. Print it with {s}; .len is the number of bytes.
  • A string literal’s type is *const [N:0]u8: a pointer to N bytes plus a zero byte. It turns into []const u8 automatically.
  • Single quotes make one character (a number); double quotes make a string.
  • \\ at the start of each line makes a multiline string, with no escapes.
  • Text is UTF-8: non-English characters can take several bytes, and indexing gives bytes.
  • Compare with std.mem.eql(u8, a, b), never ==. Join literals with ++; build runtime text with std.mem.print.

Next up: Zig Type Casting, how to turn one type into another on purpose.

Quick check

1. What is the usual type for a piece of text in Zig?
2. What is "café".len?
3. How do you check whether two strings a and b have the same text?
4. What does 'A' (single quotes) give you?