3

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

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

有没有办法将数组变回字符串?

4

2 回答 2

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 实例方法可用于获取 Int的 Unicode 代码点。然后,您.join将单个字符转换为新字符串。

于 2017-09-19T06:58:50.707 回答
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€æ∡”

于 2017-09-19T00:14:05.110 回答