Hi to you all,
suppose I have given the string expression “1-5”. I would like to convert this to a true integer vector, i.e. [1, 2, 3, 4, 5]. That seems to be a bit tricky to me. Could someone give me a hint ?
Thanks
Hi to you all,
suppose I have given the string expression “1-5”. I would like to convert this to a true integer vector, i.e. [1, 2, 3, 4, 5]. That seems to be a bit tricky to me. Could someone give me a hint ?
Thanks
Here is one way, using a regular expression, parse
and collect
:
julia> str = "1-5";
julia> function range_str_to_vec(str)
m = match(r"(\d+)\-(\d+)", str)
m === nothing && error("good error message")
r = parse(Int, m[1]) : parse(Int, m[2])
collect(r)
end;
julia> range_str_to_vec(str)
5-element Vector{Int64}:
1
2
3
4
5
Depending on your usecase you might be able to skip the collect since a range behaves more or less like a regular vector, but saves memory.
If you are not familiar to regular expression and the form will be not broken, then split
function may be an easier way.
julia> input = "1-5"
"1-5"
julia> (a,b) = parse.(Int64, (split(input, '-')))
2-element Vector{Int64}:
1
5
julia> collect(a:b)
5-element Vector{Int64}:
1
2
3
4
5
Both solutions are great. Thank you very much!