Generate equal length strings from numbers by padding with "0"?

Let’s say I have an array of integers x = [1, 14, 356].
I want to generate individual strings, with equal lengths: x_str = [“001”, “014”, “356”].
How can I achieve that?

The background of the problem is the following: I started playing with CImGui.jl (it’s awesome!) and I want to automatically generate checkboxes which will be used to edit frames for an SPI communication.
I managed to create the checboxes, but because of the variable length of their names, they are not aligned horizontally.

I could search through the ImGui documentation on how to align them, but since I thought of this workaround I’m curious if there’s a simple(one line-ish)_ solution to generate equal length strings by padding with “0”.

julia> x = [1, 14, 356];

julia> function pad_zeros(x)
           strs = string.(x)
           m = maximum(length, strs)
           lpad.(x, m, "0")
       end
pad_zeros (generic function with 1 method)

julia> pad_zeros(x)
3-element Array{String,1}:
 "001"
 "014"
 "356"
4 Likes

Thank you! This is exactly what I needed! I didn’t know the lpad function.

Actually lpad does the “stringification” behind the scenes :wink:

julia> x = [1, 14, 356]
3-element Array{Int64,1}:
   1
  14
 356

julia> [lpad(_x, 3, "0") for _x ∈ x]
3-element Array{String,1}:
 "001"
 "014"
 "356"
4 Likes

But where did your 3 come from? I think it’s worth converting them to strings for the sake of:

m = maximum(length, strs)

Although, this may yield better performance

function pad_zeros(x)
    m = floor(Int, maximum(y -> y > 0 ? log10(y) : log10(-y)+1, x)) + 1
    lpad.(x, m, "0")
end

(But I find this less readable, and I’d be extremely surprised if lpad is a performance bottle neck…)

Yep, the 3 was just to demonstrate the approach. Of course a non-hardcoded version is preferable, always :wink:

1 Like

The [lpad(_x, 3, "0") for _x ∈ x] with hardcoded number of zeros will also work because my application will never use bitfields larger than 64 bits. Of course, using the pad_zeros function is more future proof. Performance is not critical for this application.

1 Like