How to join strings in Elixir?

If what you have is an arbitrary list, then you can use Enum.join, but if it's for just two or three, explicit string concatenation should be easier to read

"StringA" <> " " <> "StringB"

However, often you don't need to have it as a single string in memory if you're going to output it through e.g. the network. In that case, it can be advantageous to use an iolist (a specific type of a deep list), which saves you from copying data. For example,

iex(1)> IO.puts(["StringA", " ", "StringB"])
StringA StringB
:ok

Since you would have those strings as variables somewhere, by using a deep list, you avoid allocating a whole new string just to output it elsewhere. Many functions in elixir/erlang understand iolists, so you often wouldn't need to do the extra work.


Answering for completeness, you can also use String interpolation:

iex(1)> [a, b] = ["StringA", "StringB"]
iex(2)> "#{a} #{b}"
"StringA StringB"

If you just want to join some arbitrary list:

"StringA" <> " " <> "StringB"

or just use string interpolation:

 "#{a} #{b}"

If your list size is arbitrary:

Enum.join(["StringA", "StringB"], " ")

... all of the solutions above will return

"StringA StringB"

Tags:

Elixir