Strings are binaries with UTF-8 codepoints in them. You create a string with the usual double-quote syntax:
iex> "hey, a string" "hey, a string"
Charlists are, as the name implies, lists of character codes. You create them using the single-quote syntax:
iex> 'hey, a charlist' 'hey, a charlist'
Since this is just a list, you can use the hd function to get the code for the first character:
iex> hd('hey, a charlist') 104
You can find out the code of a certain character with the ? operator. For instance, to find out the character code of a lowercase d, you'd use ?d.
Both representations support string interpolation:
iex> "two plus two is: #{2+2}" "two plus two is: 4" iex> 'four minus one is: #{4-1}' 'four minus one is: 3'
Both representations also support the heredoc notation, which is most commonly used to write documentation. To create it, use three single or double quotes:
iex> """ ...> a string with heredoc notation ...> """ "a string with heredoc notation\n" iex> ''' ...> a charlist with heredoc notation ...> ''' 'a charlist with heredoc notation\n'
The closing delimiter of a heredoc string/charlist must be on its own line.
Elixir provides sigils as another syntax to declare strings or charlists, which can be handy if you want to include quotes inside your string. You can use ~s to create a string and ~c to create a charlist (their uppercase versions, ~S and ~C, are similar but don't interpolate or escape characters):
iex> ~s(a string created by a sigil) "a string created by a sigil" iex> ~c(a charlist created by a sigil) 'a charlist created by a sigil'
There's another sigil that's worth mentioning: ~r, which is used for regular expressions. In the next snippet, we're using the run function from the Regex module to exemplify the usage of the ~r sigil:
iex> Regex.run(~r{str}, "a string") ["str"] iex> Regex.run(~r{123}, "a string") nil
The convention in the Elixir community is to only use the term string when referring to the double-quote format. This distinction is important, since their implementation is very different. Functions from the String module will only work on the double-quote format. You should always use the double-quote format, unless you're required to use a charlist—which is the case, for instance, when you're using Erlang libraries. You can use the following functions to convert between the two formats:
iex> String.to_charlist("converting to charlist") 'converting to charlist' iex> List.to_string('converting to string') "converting to string"