Sample code for 30+ languages & platforms
Zig

Unicode Escape

Convert a string to Unicode escaped values.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    const sb = try chilkat.StringBuilder.init();
    defer sb.deinit();

    const str = "bôn";
    const charset = "not_used";

    // Unicode escape all chars using \uHHHH
    try sb.setString(str);
    sb.encode("unicode-escape-all", charset) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    // Output is \u0062\u00f4\u006e

    // Unicode escape only 8bit chars using \uHHHH
    try sb.setString(str);
    sb.encode("unicode-escape-8bit", charset) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    // Output is b\u00f4n

    // To use uppercase hex chars (A-F), add "-upper" to the encoding name
    try sb.setString(str);
    sb.encode("unicode-escape-all-upper", charset) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    // Output is \u0062\u00F4\u006E

    // Unicode escape all chars using \u{HHHH}
    try sb.setString(str);
    sb.encode("unicode-escape-all-curly-upper", charset) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    // Output is \u{0062}\u{00F4}\u{006E}

    // Unicode escape 8bit chars using HTML hex &#xH;
    try sb.setString(str);
    sb.encode("unicode-escape-8bit-html-hex", charset) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    // Output is bôn

    // Unicode escape all chars using HTML decimal &#D;
    try sb.setString(str);
    sb.encode("unicode-escape-all-html-dec", charset) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    // Output is bôn

    // Unicode escape all chars using u+HHHH
    try sb.setString(str);
    sb.encode("unicode-escape-all-plus", charset) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    // Output is u+0062u+00f4u+006e

    // Unicode escape 8bit chars using angled brackets <HHHH>
    try sb.setString(str);
    sb.encode("unicode-escape-8bit-angle-upper", charset) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    // Output is b<00F4>n
}