📌
【Zig】文字とコードポイントの相互変換
std.debug.print
でコードポイントを調べることもできる。1文字をシングルクォートで囲む。複数のコードポイントで構成される文字列は利用できない
const std = @import("std");
const print = std.debug.print;
pub fn main() !void {
print("{u}\n", .{ 0x3042 });
print("U+{X}\n", .{ 'あ' });
print("{}\n", .{ comptime_int == @TypeOf('あ')});
}
一般的なバイト列に関して std.unicode
の utf8Encode
と utf8Decode
を使う
const std = @import("std");
const print = std.debug.print;
const utf8Encode = std.unicode.utf8Encode;
const utf8Decode = std.unicode.utf8Decode;
pub fn main() !void {
var buf: [4]u8 = undefined;
_ = try utf8Encode(0x3042, buf[0..]);
var cp = try utf8Decode("あ");
print("{s}\n", .{ buf });
print("U+{X}\n", .{ cp });
}
文字からのコードポイントの変換に関してイテレーターを使うこともできる
const std = @import("std");
const print = std.debug.print;
const unicode = std.unicode;
pub fn main() !void {
const s = "あいうえお";
var it = (try unicode.Utf8View.init(s)).iterator();
const cp = it.nextCodepoint().?;
print("U+{X}\n", .{ cp });
}
Discussion