代码之家  ›  专栏  ›  技术社区  ›  Pigna

如何将整数转换为字符

  •  2
  • Pigna  · 技术社区  · 9 年前

    我有一组整数ns,其中0<=n<=9表示ns中的所有n。我需要将它们保存为字符或字符串。我用@time来比较内存使用情况,得到了以下结果:

    julia> @time a = "a"
      0.000010 seconds (84 allocations: 6.436 KiB)
    "a"
    
    julia> @time a = 'a'
      0.000004 seconds (4 allocations: 160 bytes)
    'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
    
    1. 为什么会有如此巨大的差异?

    Char(1) 在我收到的回复中 '\x01': ASCII/Unicode U+0001 (category Cc: Other, control) 如果我试着打印它,我会得到这个符号:。

    '1' 在我收到的回复中 '1': ASCII/Unicode U+0031 (category Nd: Number, decimal digit) 如果我把它打印出来 1 . 这就是我想要的行为。

    我曾想过创建一个字典,为每个整数指定其对应的字符,但我很确定这不是一个好办法。。。

    2 回复  |  直到 9 年前
        1
  •  3
  •   Dan Getz    9 年前

    使用 Char(n + '0') . 这将添加 0 数字并固定其余数字。例如:

    julia> a = 5
    5
    
    julia> Char(a+'0')
    '5': ASCII/Unicode U+0035 (category Nd: Number, decimal digit)
    

    另请注意 @time @btime 或 @benchmark

        2
  •  1
  •   Liso    9 年前

    你可能需要这样的东西:

    julia> bunch_of_integers = [1, 2, 3, 4, 5]
    
    julia> String(map(x->x+'0', bunch_of_integers))
    "12345" 
    

    julia> map(Char, bunch_of_integers.+'0')
    5-element Array{Char,1}:
     '1'
     '2'
     '3'
     '4'
     '5'