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"
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.