Elixir Course Online | Prograils - Software Development Company
Strings
Representation
In Elixir there are two types of "strings":
double-quoted strings:
"hello"
,single-quoted strings:
'hello'
.
These are two different types and values. To prove that let's compare them:
iex> "hi" === 'hi'
false
iex> "hi" == 'hi'
false
By convention, in Elixir, double-quoted version is called string and single-quoted character list.
String literals similarities
You already know that string and character list are two different things. There are however some similarities:
both are UTF-8 encoded binary,
they may contain escape sequences (escape characters list),
both allow interpolation.
Character list
How exactly is character list different from a string? On a low level, single-quoted strings are represented as a list of integers values, each value corresponding to a codepoint in the string. Here is a proof that we should treat it as a list:
iex> is_list 'hello'
true
iex> is_list "hello"
false
Furthermore, if IEx
believes each number in the list is a printable character, it will print it as a character list:
iex> [104, 101, 108, 108, 111]
'hello'
If you want to operate on a string as a list, you should consider using the single-quoted version.
Sigils
You can declare both strings and char lists with sigils:
strings
iex> ~s(this is a string with "double" quotes, not 'single' ones) "this is a string with \"double\" quotes, not 'single' ones"
char lists
iex> ~c(this is a char list containing 'single quotes') 'this is a char list containing \'single quotes\''
String operators
Interpolation
You can interpolate a value inside of a string with #{...}
:
iex> min_age = 18
18
iex> current_age = 16
16
iex> "In #{18 - 16} years you will be an adult!"
"In 2 years you will be an adult!"
Concatenation
You can concatenate two string with <>
operator:
iex> "Hello " <> "world"
"Hello world"