xiaodai
xiaodai

Reputation: 16004

Julia: How do I cut a String into an Arrary{String}?

I have a super long string (think millions of letters) and I want to cut it into an array of Strings given an array of lengths. E.g.

string1 = "abcdefgh"

split_into_array(string1, lengths) = ....

such that

split_into_array("abcdefgh", [2,3,1,2])

should give

["ab", "cde", "f", "gh"]

Also, I don't need the original string anymore, so it's better if it's a no-copy solution.

Upvotes: 1

Views: 93

Answers (2)

Djaouad
Djaouad

Reputation: 22776

You can use string slicing:

function split_into_array(str::String, len::Array{Int})
  j = 1
  r = Array{String}(undef, length(len))
  for (i, n) in enumerate(len)
    r[i] = str[j:j + n - 1]
    j += n
  end
  return r
end

@show split_into_array("abcdefgh", [2, 3, 1, 2])

Output:

split_into_array("abcdefgh", [2, 3, 1, 2]) = ["ab", "cde","f", "gh"]

Upvotes: 2

carstenbauer
carstenbauer

Reputation: 10127

Similar to @MrGeek's solution but using nextind because naive string slicing might fail for unicode strings.

function split_into_array(s::AbstractString, lengths::AbstractVector{Int})
    i = 1
    result = Vector{String}(undef, length(lengths))
    for (li, n) in enumerate(lengths)
        lastind = nextind(s,i,n-1)
        result[li] = s[i:lastind]
        i=lastind+1
    end
    result
end

Upvotes: 2

Related Questions