简体   繁体   中英

How to convert integer to char

I have a bunch of integers ns where 0 <= n <= 9 for all n in ns. I need to save them as characters or strings. I used @time to compare memory usage and I got this:

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. Why such a huge difference?

I chose to convert the integers into characters, but I don't understand what's the proper way to do it. When I do Char(1) in the REPL I get '\\x01': ASCII/Unicode U+0001 (category Cc: Other, control) and if I try to print it I get this symbol: .

Instead when I do '1' in the REPL I get '1': ASCII/Unicode U+0031 (category Nd: Number, decimal digit) and if I print it I get 1 . This is the behavior I want.

  1. How to achieve it?

I thought about creating a dictionary to assign to each integer its corresponding character, but I am pretty sure that's not the way to go ...

Use Char(n + '0') . This will add the ASCII offset of the 0 digit and fix the rest of the digits too. For example:

julia> a = 5
5

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

Also note, timing with @time is a bit problematic, especially for very small operations. It is better to use @btime or @benchmark from BenchmarkTools.jl .

You probably need something like:

julia> bunch_of_integers = [1, 2, 3, 4, 5]

julia> String(map(x->x+'0', bunch_of_integers))
"12345" 

or something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM