🌊

【Zig】文字列のバイト数、文字数を求める

2024/04/11に公開

const で文字列リテラルを宣言する。バイト数は len で求められる。文字数は std.unicodeutf8CountCodepoints で求められる

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

pub fn main() !void {
    const s = "あいうえお";

    print("{s}\n", .{s});
    print("バイト数: {}\n", .{s.len});
    const len = try unicode.utf8CountCodepoints(s);
    print("文字数: {}\n", .{len});
}

utf8ByteSequenceLength を使って先行バイトをもとに1文字ずつバイトサイズを計算することで文字数を求めることができる。

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

pub fn main() !void {
    const bytes = "あいうえお";
    var i: u32 = 0;
    var size: u8 = 0;
    var length:u32 = 0;

    while (i < byte.len) {
        size = try std.unicode.utf8ByteSequenceLength(bytes[i]);
        i += size;
        length += 1;
    }

    print("{d}\n", .{ length });
}

イテレーターを使って文字数を数えることもできる。nextCodepointSlice もしくは nextCodepoint を使う。

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

pub fn main() !void {
    const s = "あいうえお";
    var count:u8 = 0;

    var it  = (try unicode.Utf8View.init(s)).iterator();

    while (it.nextCodepointSlice()) |_| {
        count += 1;
    }

    print("文字数: {x}\n", .{count});
}

Discussion