最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to split a string in Julia and return a vector of strings - Stack Overflow

programmeradmin5浏览0评论

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.

Share Improve this question asked Mar 26 at 16:43 user2138149user2138149 17.6k30 gold badges146 silver badges296 bronze badges 1
  • 1 One way is to use the desired type directly on the vector, e.g. Vector{String}(split("dd ff gg jj", " ")) – Andre Wildberg Commented Mar 26 at 17:11
Add a comment  | 

2 Answers 2

Reset to default 0

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

发布评论

评论列表(0)

  1. 暂无评论