iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👻

[Zig] Concatenating Strings with ArrayList

に公開

You can concatenate multiple strings by using ArrayList.

const std = @import("std");
const expect = std.testing.expect;
const print = std.debug.print;

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    var list = std.ArrayList(u8).init(allocator);
    defer list.deinit();

    try list.append(0xe3);
    try list.append(0x81);
    try list.append(0x82);
    try list.appendSlice("いう");

    print("{s}\n", .{list.items});
}

The test code is as follows:

test.zig
const std = @import("std");
const eql = std.mem.eql;
const expect = std.testing.expect;

test "arraylist" {
    var list = std.ArrayList(u8).init(std.testing.allocator);
    defer list.deinit();
    try list.append(0xe3);
    try list.append(0x81);
    try list.append(0x82);
    try list.appendSlice("いう");

    try expect(eql(u8, list.items, "あいう"));
}

Discussion