🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Strings

A string is a sequence of bytes that represents text. Zig treats a string literal as read-only bytes with the type []const u8.

A string prints its text and byte count

The word is stored as []const u8. The printout shows the text and a length of 3 bytes.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const word: []const u8 = "Zig";
    try out.print("{s}\n", .{word});
    try out.print("{d}\n", .{word.len});
}

One byte prints as a character and as a number

The first byte of the word is the letter c. It prints as c with {c} and as its byte value 99 with {d}.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const word: []const u8 = "code";
    try out.print("{c}\n", .{word[0]});
    try out.print("{d}\n", .{word[0]});
}

A sub-slice cuts out the middle

The slice starts at index 1 and ends before index 4. It prints the three bytes in between.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const word: []const u8 = "hello";
    const part = word[1..4];
    try out.print("{s}\n", .{part});
    try out.print("{d}\n", .{part.len});
}

Example

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const word: []const u8 = "banana";
    var count: i32 = 0;
    for (word) |ch| {
        if (ch == 'a') {
            count += 1;
        }
    }
    try out.print("{s}\n", .{word});
    try out.print("{d}\n", .{word.len});
    try out.print("{c}\n", .{word[0]});
    try out.print("{s}\n", .{word[0..3]});
    try out.print("{d}\n", .{count});
}

Key points

  • String literal: text in double quotes, such as "Zig", is a string.
  • Byte type: a string used as []const u8 is a sequence of bytes, and u8 is a single byte.
  • Length: .len counts the bytes in the string.
  • First byte: word[0] reads the first byte, and {c} prints a byte as a character.
  • Sub-slice: word[1..4] takes a smaller string that starts at index 1 and ends before index 4.
  • Byte loop: a for loop over a string visits one byte at a time.

In this example, the loop visits each byte of banana and counts the bytes equal to the letter a. The printouts then show the word, its length 6, its first byte b, the opening slice ban, and the count 3.

Note

comparing string contents needs a helper from the standard library, not ==.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is the type of a string when it is stored as text bytes in this course?