Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: how to concatenate characters of vector together (["a", "b", "c"] -> "abc")

How to concatenate characters or strings in a vector together in one string so that ["a", "b", "c"] becomes "abc"?

I've tried with vcat, hcat, but nothing seems to work... Thank you

Answer

join(["a", "b", "c"])

like image 519
Dominique Makowski Avatar asked Aug 28 '18 13:08

Dominique Makowski


2 Answers

There are a variety of ways to concatenate a vector of strings:

  • join function
  • string function
  • * concatenate function

as shown by the various comments.

However, the calling signatures for these functions are not identical. I did not notice this at first, and someone else new to Julia might appreciate the details.

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

However, when someone, like myself, is new to Julia, they might not immediately recognize (I didn't) the critical importance of ... for the string and * string concatenate functions, in contrast to the join function.

For example:

julia> s2 = string(a)
"[\"a\", \"b\", \"c\"]"

julia> s == s2
false

# or simply:
julia> join(a) == string(a)
false

What is the difference between s = join(a) and 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"

The *() concatenation function is also quite different from the join function:

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"

Thus the "splat" operator, ..., which is used to apply a function to a sequence of arguments is crucial to string and *, but not to join.

In fact, the join function with the "splat" operator does something you probably don't want:

julia> join(a...)
"a"
like image 133
Julia Learner Avatar answered Nov 10 '22 09:11

Julia Learner


a = ["a", "b", "c"]; string(a...)

join(["a", "b", "c"])

like image 45
Dominique Makowski Avatar answered Nov 10 '22 09:11

Dominique Makowski