> "✭" iex> "x{272d}" "✭" 但我需-6ren">
gpt4 book ai didi

unicode - 如何将 Unicode 代码点转换为 Unicode 字符串?

转载 作者:行者123 更新时间:2023-12-02 10:52:53 33 4
gpt4 key购买 nike

我有一个表示 Unicode 代码点的字符串,例如 "272d"。如何将其转换为 "✭"

Elixir 当然理解 Unicode:

iex> << 10029 :: utf8 >>
"✭"

iex> "x{272d}"
"✭"

但我需要一个接受四个字符并返回 Unicode 字符串的函数:

def from_code_point(<< code_point :: size(32) >>) do
???
end

或者可能

def from_code_point(<< a, b, c, d >>) do
???
end

我也尝试过将其作为宏:

defmacro from_code_point(<< code_point :: size(32) >>) do
quote do
"x{unquote(code_point)}"
end
end

但这只是返回“x{unquote(code_point)}”

最佳答案

Unicode 代码点是一个数字,因此您需要做的第一件事是解析字符串以查看它代表什么值。您可以使用 binary_to_integer/2 (在 R16 中可用,对于 R15,您需要依次执行 binary_to_list/1list_to_integer/2

一旦获得了代码点的数值,您就可以通过告诉 Elixir 您传递的数字是一个 Unicode 代码点,将其简单地以二进制形式(这是字符串的底层表示形式)存储起来,如下所示

def to_string(input) do
<<binary_to_integer(input, 16) :: utf8>>
end

如果您必须从较大的字符串中提取它,则可以将 String.slice/3 放在中间,如下所示

def to_string2(input) do
codepoint = String.slice(input, 0, 4)
<<binary_to_integer(codepoint, 16) :: utf8>>
end

关于unicode - 如何将 Unicode 代码点转换为 Unicode 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17775978/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com