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.
A string is a slice of bytes
Section titled “A string is a slice of bytes”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:
Hellolength: 5first byte: H (72){s}prints the bytes as text. If you forget thesand write{}, the build fails withcannot format slice without a specifier..lenis the number of bytes.greeting[0]is the first byte, au8.{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.
What a string literal really is
Section titled “What a string literal really is”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]u8That 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.
Single quotes are for one character
Section titled “Single quotes are for one character”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 65A is a string of 1 byteMixing 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.
Escape sequences
Section titled “Escape sequences”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 oneLine twoName: AdaShe said "hi"A path: C:\Users\adaA 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.
Multiline strings
Section titled “Multiline strings”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 tasksThere 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:
Helloword 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).
UTF-8: .len counts bytes, not letters
Section titled “UTF-8: .len counts bytes, not letters”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: 5characters: 463 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.
Comparing strings
Section titled “Comparing strings”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: trueis help: falsestarts with q: trueThe 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.
Slicing and joining
Section titled “Slicing and joining”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 11Hello, 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.
Practice
Section titled “Practice”1. Initials
Section titled “1. Initials”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.
2. Check the password
Section titled “2. Check the password”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 grantedstd.mem.eql returns true only when both slices have the same length and the same bytes.
3. Bytes vs characters
Section titled “3. Bytes vs characters”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};.lenis 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 u8automatically. - 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 withstd.mem.print.
Next up: Zig Type Casting, how to turn one type into another on purpose.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: String Literals: the type of string literals, UTF-8 and code point literals.
- Zig language reference: Multiline String Literals: the
\\syntax in detail. - Zig language reference: Slices: what
[]const u8really is. - Zig standard library docs: look up
std.memandstd.unicodefor string helpers.