如何将向量中的字符或字符串连接在一个字符串中,以便[“a”,“b”,“c”]变为“abc”?
我试过用vcat,hcat,但似乎没什么用......谢谢
join(["a", "b", "c"])
有多种方法可以连接字符串向量:
join
功能string
功能*
连接函数如各种评论所示。
但是,这些功能的呼叫签名并不相同。起初我没有注意到这一点,而朱莉娅的新人可能会欣赏细节。
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
然而,当像我这样的人对朱莉娅来说是新手时,他们可能不会立即认识到(我没有)...
对于string
和*
字符串连接函数的重要性,与join
函数形成对比。
例如:
julia> s2 = string(a)
"[\"a\", \"b\", \"c\"]"
julia> s == s2
false
# or simply:
julia> join(a) == string(a)
false
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"
*()
连接函数也与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"
因此,用于将函数应用于一系列参数的“splat”运算符...
对string
和*
至关重要,但对join
则不重要。
事实上,join
函数与“splat”运算符做了一些你可能不想要的事情:
julia> join(a...)
"a"
a = ["a", "b", "c"]; string(a...)
join(["a", "b", "c"])