pranphy
pranphy

Reputation: 1889

Split array, into array of arrays, by a value

What would be the best way of converting the array

["a", "bc", "", "d", "efg", "", "ijkl"]

after splitting it with "" into

[["a","bc"],["d","efg"],["ijkl"]]

in Julia.

Upvotes: 2

Views: 650

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

It depends what you mean by "best". Here is one way to do it:

julia> x = ["a", "bc", "", "d", "efg", "", "ijkl"]
7-element Array{String,1}:
 "a"
 "bc"
 ""
 "d"
 "efg"
 ""
 "ijkl"

julia> loc = findall(isempty, x)
2-element Array{Int64,1}:
 3
 6

julia> getindex.(Ref(x), UnitRange.([1; loc .+ 1], [loc .- 1; length(x)]))
3-element Array{Array{String,1},1}:
 ["a", "bc"]
 ["d", "efg"]
 ["ijkl"]

And here is another one:

julia> function splitter(x)
           out = Vector{Vector{eltype(x)}}()
           cur = eltype(x)[]
           for s in x
               if isempty(s)
                   push!(out, cur)
                   cur = eltype(x)[]
               else
                   push!(cur, s)
               end
           end
           push!(out, cur)
           return out
       end
splitter (generic function with 1 method)

julia> splitter(x)
3-element Array{Array{String,1},1}:
 ["a", "bc"]
 ["d", "efg"]
 ["ijkl"]

Upvotes: 2

Related Questions