簡體   English   中英

如何在 Zig 中打印 UTF-16 字符串?

[英]How do I print a UTF-16 string in Zig?

我一直在嘗試編寫 UTF-16 字符串結構,盡管標准庫提供了unicode模塊,但它似乎沒有提供打印出u16切片的方法。 我試過這個:

const std = @import("std");
const unicode = std.unicode;
const stdout = std.io.getStdOut().outStream();

pub fn main() !void {
    const unicode_str = unicode.utf8ToUtf16LeStringLiteral("😎 hello! 😎");
    try stdout.print("{}\n", .{unicode_str});
}

這輸出:

[12:0]u16@202e9c

有沒有辦法打印 unicode 字符串( []u16 )而不將其轉換回非 unicode 字符串( []u8 )?

[]const u8[]const u16存儲編碼的 unicode 代碼點。 Unicode 代碼點適合在 0..1,114,112 范圍內,因此每個代碼點具有一個數組索引的實際 Unicode 字符串必須是[]const u21 utf-8 和 utf-16 都需要對不適合的代碼點進行編碼。 除非出於 utf-16 的兼容性原因(如某些 Windows 函數),否則您可能應該使用[]const u8 unicode 字符串。

要將 utf-16 打印到 utf-8 流,您必須解碼 utf-16 並將其重新編碼為 utf-8。 目前沒有格式說明符可以自動執行此操作。

您可以一次轉換整個字符串,需要分配:

const utf8string = try std.unicode.utf16leToUtf8Alloc(alloc, utf16le);

或者,沒有分配:

var writer = std.io.getStdOut().writer();
var it = std.unicode.Utf16LeIterator.init(utf16le);
while (try it.nextCodepoint()) |codepoint| {
    var buf: [4]u8 = [_]u8{undefined} ** 4;
    const len = try std.unicode.utf8Encode(codepoint, &buf);
    try writer.writeAll(buf[0..len]);
}

請注意,如果您正在編寫需要系統調用寫入的地方,那么如果不使用緩沖寫入器,這將非常慢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM