如何将一个代码点数组(Int32)转换为字符串?

时间:2017-09-19 00:03:15

标签: string crystal-lang codepoint

在Crystal中,String可以转换为代码点的数组(Int32):

"abc".codepoints # [97,98,99] 

有没有办法将Array转回String?

2 个答案:

答案 0 :(得分:2)

  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将各个字符转换为新字符串。

答案 1 :(得分:1)

这是一种方式:

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€æ∡”