【问题标题】:How do you turn an Array of codepoints (Int32) to a string?如何将代码点数组(Int32)转换为字符串?
【发布时间】:2017-09-19 00:03:15
【问题描述】:

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

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

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

【问题讨论】:

    标签: string crystal-lang codepoint


    【解决方案1】:
      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 单个字符转换为一个新字符串。

    【讨论】:

      【解决方案2】:

      这是一种方法:

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

      【讨论】:

        猜你喜欢
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-15
        • 1970-01-01
        • 2016-01-26
        • 2019-07-23
        相关资源
        最近更新 更多