Chuyển đến nội dung

Bài 10 · Language Basics

Strings and Characters

Learn how Zig handles text: strings as byte slices, string literals and sentinels, multiline strings, comparing with std.mem.eql, searching, splitting, formatting and UTF-8 basics.

Zig has no string type. Text is just a slice of bytes: []const u8. That sounds primitive, but it is honest and powerful: a string is a pointer and a length, you decide who owns the bytes, and everything you learned about slices applies. The standard library supplies the helpers (std.mem, std.fmt, std.ascii, std.unicode) that other languages put into a string class.

String literals

A literal such as "hello" is stored in the program's read-only data. Its type is *const [5:0]u8: a pointer to a constant array of 5 bytes followed by a zero byte (the sentinel). That pointer coerces to the slice type []const u8, so you can pass literals wherever text is expected, and also to C functions that expect null-terminated strings.

ZIG
const std = @import("std");

pub fn main() void {
    const greeting: []const u8 = "Hello, Zig";

    std.debug.print("{s}\n", .{greeting});
    std.debug.print("length: {d}\n", .{greeting.len});
    std.debug.print("first byte: {d} ('{c}')\n", .{ greeting[0], greeting[0] });
    std.debug.print("last word: {s}\n", .{greeting[7..]});
}
TEXT
Hello, Zig
length: 10
first byte: 72 ('H')
last word: Zig

.len counts bytes, not characters. For ASCII they are the same; for other scripts they are not (see UTF-8 below).

Escapes, characters and multiline strings

Escapes: \n newline, \t tab, \\ backslash, \" quote, \xNN a byte, \u{1F600} a Unicode code point written as UTF-8.

A single-quoted literal is a character code: 'A' is a comptime_int with the value 65 (it fits in a u8), and '\u{1F600}' is a code point that needs u21.

ZIG
const newline_count: u8 = '\n';        // 10
const smile = "\u{1F600}";             // 4 bytes in UTF-8

Multiline strings use \\ at the start of each line. There are no escapes inside, and the line breaks are kept:

ZIG
const poem =
    \\Roses are red,
    \\Zig is fast,
    \\no hidden allocations,
    \\built to last.
;

The final ; goes on its own line. This form is ideal for SQL, JSON and help messages.

Comparing, searching and splitting

Because == does not compare slice contents, use std.mem:

ZIG
const std = @import("std");
const mem = std.mem;

pub fn main() void {
    const text = "one,two,three";

    std.debug.print("{}\n", .{mem.eql(u8, "zig", "zig")});          // true
    std.debug.print("{}\n", .{mem.startsWith(u8, text, "one")});    // true
    std.debug.print("{}\n", .{mem.endsWith(u8, text, "four")});     // false
    std.debug.print("{?d}\n", .{mem.indexOf(u8, text, "two")});     // 4
    std.debug.print("{?d}\n", .{mem.indexOfScalar(u8, text, 'x')}); // null

    var parts = mem.splitScalar(u8, text, ',');
    while (parts.next()) |part| {
        std.debug.print("[{s}]\n", .{part});
    }
}
TEXT
true
true
false
4
null
[one]
[two]
[three]

Other useful functions: mem.trim(u8, s, " \n"), mem.tokenizeAny (skips empty pieces), mem.splitSequence (split on a multi-byte separator), mem.count, mem.replace (needs a buffer), std.ascii.toUpper, std.ascii.isDigit. The return value of indexOf is an optional (?usize), covered in the optionals lesson, which is why {?d} prints null when nothing is found.

Function names in std.mem have been reorganized across versions (split became splitScalar, splitSequence and splitAny), which is a classic reason an old tutorial fails to compile.

Building strings

Zig will not concatenate runtime strings with +. Options:

  • a ++ b joins compile-time known strings.
  • std.fmt.bufPrint(&buffer, "{s}-{d}", .{ name, id }) formats into a buffer you own and returns the used slice or an error if it does not fit.
  • std.fmt.allocPrint(allocator, ...) allocates the result; you free it.
  • std.ArrayList(u8) with a writer builds text step by step (covered in the allocators chapter).
ZIG
var buffer: [64]u8 = undefined;
const label = try std.fmt.bufPrint(&buffer, "{s}-{d:0>4}", .{ "item", 42 });
// label is "item-0042"

bufPrint shows the style of the whole language: the caller supplies memory, so there is no hidden allocation.

Mutable strings

String literals are constant. To edit text, copy it into a var array or an allocated buffer first:

ZIG
var word = [_]u8{ 'z', 'i', 'g' };
word[0] = std.ascii.toUpper(word[0]);
// word is now "Zig"

UTF-8

Source files and literals are UTF-8. A []const u8 can hold any bytes, but Unicode characters beyond ASCII occupy 2 to 4 bytes. "héllo".len is 6, not 5, because é takes two bytes. To walk characters (code points) use std.unicode.Utf8View:

ZIG
const std = @import("std");

pub fn main() !void {
    const text = "h\u{00E9}llo";   // "héllo"
    std.debug.print("bytes: {d}\n", .{text.len});

    const view = try std.unicode.Utf8View.init(text);
    var it = view.iterator();
    var count: usize = 0;
    while (it.nextCodepoint()) |_| count += 1;
    std.debug.print("code points: {d}\n", .{count});
}
TEXT
bytes: 6
code points: 5

Even code points are not always what a user calls a "character" (accents can be separate code points). Zig's standard library stays at the code point level; grapheme handling lives in third-party packages.

Sentinel-terminated strings and C

[:0]const u8 is a slice that promises a zero byte right after its end. It is what C functions want. A normal slice may point into the middle of a longer string, so it has no such guarantee. Convert with std.mem.span (from a C pointer to a slice) or by allocating with allocator.dupeZ(u8, slice).

Stand-ins you can run

C's string functions are the ancestors of std.mem. This stand-in does the same comparison, search and split as the Zig example, with the length-carrying slice type made explicit.

C Stand-in (C): string slices, comparing, searching, splitting

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust Stand-in (Rust): bytes versus characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is Zig's usual type for text?

    Text is a slice of bytes; Zig has no built-in string type.
  2. 2. How do you test whether two strings have equal contents?

    std.mem.eql compares the bytes of two slices.
  3. 3. What is "h\u{00E9}llo".len?

    The accented e is two bytes in UTF-8, so the string has 6 bytes but 5 code points.
  4. 4. Which syntax writes a multiline string literal?

    Each line starts with two backslashes, and no escape processing happens inside.
  5. 5. Why can't you build a runtime string with a + b?

    Use ++ for compile-time strings, or format into a buffer or allocated memory you control.

Summary

  • Strings are []const u8 slices; literals have a hidden zero terminator and coerce to slices.
  • .len counts bytes; use std.unicode to count code points.
  • Compare with std.mem.eql, search with indexOf, split with splitScalar, format with bufPrint.
  • Multiline literals use \\ line prefixes; \u{...} writes Unicode.
  • Runtime concatenation needs a buffer or an allocator you provide.

Next: if and switch

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.