【发布时间】:2017-09-19 00:03:15
【问题描述】:
在 Crystal 中,可以将 String 转换为代码点的 Array(Int32):
"abc".codepoints # [97,98,99]
有没有办法将数组转回字符串?
【问题讨论】:
标签: string crystal-lang codepoint
在 Crystal 中,可以将 String 转换为代码点的 Array(Int32):
"abc".codepoints # [97,98,99]
有没有办法将数组转回字符串?
【问题讨论】:
标签: string crystal-lang codepoint
str = "aа€æ∡"
arr = str.codepoints # Array(Int32)
new_str = arr.map { |x| x.chr }.join
puts str
puts new_str
puts(str == new_str)
.chr instance method 可用于获取 Int 的 Unicode 代码点。然后您将.join 单个字符转换为一个新字符串。
【讨论】:
这是一种方法:
arr = "abc".codepoints
# The line below allocates memory and returns a "safe" pointer (ie slice) to it.
# The allocated memory is on the heap with size:
# arr.size * sizeof(0_u8)
# sizeof(0_u8) == 8 bits
# A slice of uint8 values (i.e. `Slice(UInt8)`) is aliased
# in Crystal as `Bytes`.
bytes = Slice.new(arr.size, 0_u8)
# You can also use the alias: Bytes.new(arr.size, 0_u8)
arr.each_with_index { |v, i|
bytes[i] = v.to_u8
}
puts String.new(bytes).inspect # => "abc"
但是,对于多字节代码点,上述方法失败:“a€æ∡”
【讨论】: