The String
split
function splits a Julia String
datatype and returns a Vector{SubString{String}}
.
What is the most straightforward way to return a Vector{String}
instead of substrings?
Additional info:
It seems relatively obvious that Julia returns a Vector{SubString}
as an optimization to avoid copying all of the data contained within the original String
.
However in this case, I wish to pass one of these substrings to a function which can only take a String
as an argument.
The String
split
function splits a Julia String
datatype and returns a Vector{SubString{String}}
.
What is the most straightforward way to return a Vector{String}
instead of substrings?
Additional info:
It seems relatively obvious that Julia returns a Vector{SubString}
as an optimization to avoid copying all of the data contained within the original String
.
However in this case, I wish to pass one of these substrings to a function which can only take a String
as an argument.
2 Answers
Reset to default 0You can use a list rexpression:
[String(x) for x in split("abc def")]
Which gives a Vector{String}
:
## 2-element Vector{String}:
## "abc"
## "def"
You could define that if 2 Strings are given, output should be Vector{String}:
splitS(str::String, dlm::String=" ") = [String(x) for x in split(str, dlm)]
Then this works:
julia> splitS("abc def")
2-element Vector{String}:
"a"
"b"
Or @AndreWildberg's coercion:
splitS(str::String, dlm::String=" ") = Vector{String}(spit(str, dlm))
this is actually more elegant and shorter.
Use broadcasting
julia> string.(split("a b c", ' '))
3-element Vector{String}:
"a"
"b"
"c"
julia> String.(split("a b c", ' '))
3-element Vector{String}:
"a"
"b"
"c"
both string
and String
are here equivalent in terms of performance.
Vector{String}(split("dd ff gg jj", " "))
– Andre Wildberg Commented Mar 26 at 17:11