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

Unicode 如何在Zig中打印UTF-16字符串?,unicode,utf-16,zig,Unicode,Utf 16,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.utf8ToUtf16L

我一直在尝试编码一个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("Both 
[]const u8
and
[]const u16
store encoded unicode codepoints. Unicode codepoints fit within the range 0..1,114,112 so an actual unicode string with one array index per codepoint would have to be
[]const u21
. utf-8 and utf-16 both require encoding for codepoints that don't fit. Unless there is a compatability reason for utf-16 (like some windows functions), you should probably be using
[]const u8
unicode strings.

To print utf-16 to a utf-8 stream, you have to decode utf-16 and re-encode it into utf-8. There is currently no formatting specifier to do this automatically.

You can either convert the entire string at once, requiring allocation:

const utf8string = try std.unicode.utf16leToUtf8Alloc(alloc, utf16le);
const std=@import(“std”);
常量unicode=标准unicode;
常量stdout=std.io.getStdOut().outStream();
pub fn main()!空虚{

const unicode_str=unicode.utf8ToUtf16LeStringLiteral(“两个
[]const u8
[]const u16
存储编码的unicode码点。unicode码点适合范围为0..1114112,因此每个码点具有一个数组索引的实际unicode字符串必须是
[]常量u21
。utf-8和utf-16都需要对不合适的代码点进行编码。除非utf-16(如某些windows函数)有兼容原因,否则您可能应该使用
[]常量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(试试它。nextCodepoint())| codepoint |{
变量buf:[4]u8=[[uU]u8{undefined}**4;
const len=try std.unicode.utf8Encode(代码点,&buf);
试试writell.writell(buf[0..len]);
}

请注意,如果您正在编写需要系统调用才能写入的内容,那么如果不使用缓冲写入程序,这将非常缓慢。

谁说UTF-8是非Unicode的?所有UTF编码(UTF-1/7/8/9/16/32…)都可以表示所有Unicode代码points@phuclv很抱歉,我成了非正式使用“unicode”一词来表示“非ASCII”的牺牲品“(例如python 3 unicode支持)有没有办法将标准输出流扩展到utf-16?@Sapphire_Brick输出流目前只写入字节和字节片。如果您有一个引人注目的用例,例如需要utf-16的平台或代码,您可以建议添加utf-16编写器和格式化程序。