Dom*_*ski 4 string concatenation character julia
如何将向量中的字符或字符串连接到一个字符串中,以便 ["a", "b", "c"] 变为 "abc"?
我已经尝试过使用 vcat、hcat,但似乎没有任何效果...谢谢
join(["a", "b", "c"])
有多种方法可以连接字符串向量:
join 功能string 功能* 连接函数正如各种评论所示。
但是,这些函数的调用签名并不相同。起初我没有注意到这一点,其他对 Julia 不熟悉的人可能会欣赏这些细节。
julia> j = join(a)
"abc"
julia> s = string(a...)
"abc"
julia> m = *(a...)
"abc"
# When called correctly all three functions return equivalent results.
julia> j == s == m
true
Run Code Online (Sandbox Code Playgroud)
但是,当有人像我一样对 Julia 不熟悉时,他们可能不会立即意识到(我没有意识到)与函数相比,...forstring和*字符串连接函数的重要性join。
例如:
julia> s2 = string(a)
"[\"a\", \"b\", \"c\"]"
julia> s == s2
false
# or simply:
julia> join(a) == string(a)
false
Run Code Online (Sandbox Code Playgroud)
s = join(a)和 和有s2 = string(a)什么区别?
# Note that join(a) produces a string of 3 letters, "abc".
julia> length(s)
3
# string(a) produces a string of punctuation characters with the letters.
julia> length(s2)
15
julia> s[1]
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> s2[1]
'[': ASCII/Unicode U+005b (category Ps: Punctuation, open)
julia> s[1:3]
"abc"
julia> s2[1:3]
"[\"a"
Run Code Online (Sandbox Code Playgroud)
该*()级联功能也从完全不同的join功能:
julia> a = ["a", "b", "c"]
3-element Array{String,1}:
"a"
"b"
"c"
julia> j = join(a)
"abc"
julia> m = *(a)
ERROR: MethodError: no method matching *(::Array{String,1})
julia> m = *(a...)
"abc"
Run Code Online (Sandbox Code Playgroud)
因此...,用于将函数应用于参数序列的“splat”运算符对stringand至关重要*,但对 则不是join。
事实上,join带有“splat”运算符的函数做了一些你可能不想要的事情:
julia> join(a...)
"a"
Run Code Online (Sandbox Code Playgroud)