如何将向量中的字符或字符串连接到一个字符串中,以便 ["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
然而 ,当有人像我一样对 Julia 不熟悉时,他们可能不会立即意识到(我没有意识到)
...
的重要性。为 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"
关于string - Julia:如何将向量的字符连接在一起( ["a"、 "b"、 "c"] -> "abc"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52059709/