2017-09-20 151 views
2

我有一堆整数ns其中0 < = n < = 9对于所有n in。我需要将它们保存为字符或字符串。我用@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. 为什么如此巨大的差异?

我选择将整数转换为字符,但我不明白什么是正确的方法来做到这一点。当我在REPL中做Char(1)时,我得到'\x01': ASCII/Unicode U+0001 (category Cc: Other, control),如果我尝试打印它,我会得到这个符号:。

相反,当我在REPL中做'1'时,我得到'1': ASCII/Unicode U+0031 (category Nd: Number, decimal digit),如果我打印它,我得到1。这是我想要的行为。

  1. 如何实现它?

我想到了创建字典分配给每个整数它对应的字符,但我敢肯定这是不是要走的路...

+2

使用'CHAR(N + '0')'。这将增加'0'数字的ASCII偏移量并修复其余的数字。 –

+2

用@时间计时有点麻烦,特别是对于非常小的操作。尝试使用来自BenchmarkTools.jl的'@ btime'或'@ benchmark',使用映射的 –

回答

3

使用Char(n + '0')。这将添加0数字的ASCII偏移量并修复其余数字。例如:

julia> a = 5 
5 

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

还要注意,与@time时间是有点问题的,特别是对于非常小的操作。最好使用BenchmarkTools.jl中的@btime@benchmark

1

你可能需要类似:

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' 
+0

似乎是矫枉过正!但是当我第一次尝试'bunch_of_integers。+'0''时,它返回了'Array {Int64,1}:[49,50,51,52,53]'也许我的REPL被溢出(或者是越野车)...... – Liso