Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 48 Β· Getting Started

Strings and Binaries

Work with Elixir strings: UTF-8 binaries, interpolation, heredocs, the String module, the difference between bytes and graphemes, and charlists vs strings.

Text in Elixir is stored as UTF-8 binaries. A string is simply a sequence of bytes that happens to be valid UTF-8 text, written in double quotes. That design makes strings compact and fast, and it explains a few things that surprise newcomers: why byte_size/1 and String.length/1 can disagree, why <> joins strings, and why there is an older text type called a charlist.

In this lesson you will write strings, interpolate values into them, use the String module, see the difference between bytes, code points and graphemes, and learn what binaries and charlists are. The Elixir code is read-only on this site; the TryIts are JavaScript stand-ins that model the byte-versus-character ideas.

Writing strings

Use double quotes. A string can hold any Unicode text, and it can span several lines:

ELIXIR
iex> "Hello, world!"
"Hello, world!"
iex> "hΓ©llo, δΈ–η•Œ, πŸ‘"
"hΓ©llo, δΈ–η•Œ, πŸ‘"
iex> "line one\nline two"
"line one\nline two"

Escape sequences work as you would expect: \n for a newline, \t for a tab, \" for a quote and \\ for a backslash. IO.puts prints them as real newlines, while IO.inspect (and IEx) show them escaped.

Interpolation puts the value of any expression inside a string with #{...}. The value is converted to text for you:

ELIXIR
iex> name = "Ana"
iex> "Hello, #{name}! 2 + 2 = #{2 + 2}"
"Hello, Ana! 2 + 2 = 4"

Concatenation uses the <> operator, which only works with strings (binaries):

ELIXIR
iex> "foo" <> "bar"
"foobar"
iex> "Total: " <> 42
** (ArgumentError) expected binary argument in <> operator but got: 42

The error is helpful: <> does not convert numbers. Use interpolation or Integer.to_string/1 instead, as in "Total: #{42}". Interpolation is almost always the cleaner choice.

Heredocs

For long text use triple double quotes. The content starts on the next line, and the closing """ decides how much leading indentation is removed:

ELIXIR
text = """
  Dear Ana,
    Thanks for joining.
  The team
  """

IO.write(text)
TEXT
Dear Ana,
  Thanks for joining.
The team

The closing delimiter sat two spaces in, so exactly two spaces were stripped from every line, and the relative indentation of the second line is kept. Heredocs also support interpolation. The ~S sigil writes a string with interpolation and escapes turned off; see sigils.

The String module

Strings are immutable, like all Elixir data, so every function returns a new string. The String module has what you need for everyday work:

ELIXIR
iex> String.upcase("elixir")
"ELIXIR"
iex> String.trim("  padded  ")
"padded"
iex> String.split("a,b,c", ",")
["a", "b", "c"]
iex> String.replace("hello", "l", "L")
"heLLo"
iex> String.contains?("hello world", "o w")
true
iex> String.starts_with?("hello", "he")
true
iex> String.slice("hello", 1, 3)
"ell"
iex> String.reverse("abc")
"cba"
iex> String.pad_leading("7", 3, "0")
"007"
iex> String.to_integer("42")
42

Notice the naming convention: functions that return a boolean end with ?, such as contains?. Most functions take the string as the first argument, which makes them work well with the pipe operator:

ELIXIR
"  Hello, Elixir  "
|> String.trim()
|> String.downcase()
|> String.split(", ")
# ["hello", "elixir"]

Bytes, code points and graphemes

"How long is this string?" has three honest answers, and Elixir lets you ask each one:

ELIXIR
iex> byte_size("hΓ©llo")
6
iex> String.length("hΓ©llo")
5
iex> byte_size("πŸ‘")
4
iex> String.length("πŸ‘")
1
  • Bytes: what is stored. In UTF-8, the letter Γ© takes 2 bytes, and the thumbs-up emoji takes 4. byte_size/1 counts these and is instant.
  • Code points: Unicode numbers such as U+00E9. String.codepoints/1 splits into them.
  • Graphemes: what a reader sees as one character. A grapheme can combine several code points, such as a flag or an emoji with a skin tone. String.length/1 and String.graphemes/1 count graphemes, and have to scan the string, so they take time proportional to its length.

Use String.length/1 for text you show to people (a "20 characters left" counter) and byte_size/1 for storage or network limits.

JS Stand-in: bytes vs characters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Binaries

A binary is a sequence of bytes, written between << and >>. A string is a binary whose bytes are valid UTF-8:

ELIXIR
iex> <<104, 105>>
"hi"
iex> <<1, 2, 3>>
<<1, 2, 3>>
iex> is_binary("hi")
true
iex> String.valid?(<<255>>)
false
iex> ?a
97
iex> <<?h, ?i>>
"hi"

IEx shows a binary as a string when every byte forms printable UTF-8 text, and as <<...>> otherwise. The expression ?a gives the code point of a character, here 97. Each number between the <<>> is one byte (0 to 255); larger numbers are cut to fit, so write them with explicit sizes (<<258::16>>) when you need more.

Binaries can be taken apart with pattern matching, which is how Elixir parses network packets and file formats:

ELIXIR
iex> <<first, rest::binary>> = "hello"
iex> first
104
iex> rest
"ello"

The ::binary part says "the rest of the bytes". You can also match a prefix of a string, as in "Hello, " <> name = "Hello, Ana", which binds name to "Ana".

JS Stand-in: a string is bytes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Charlists

Elixir has a second text type from its Erlang heritage: the charlist, a list of code points. Modern Elixir writes it with the ~c sigil:

ELIXIR
iex> ~c"hi"
~c"hi"
iex> [104, 105]
~c"hi"
iex> to_charlist("hi")
~c"hi"
iex> List.to_string(~c"hi")
"hi"
iex> is_list(~c"hi")
true
iex> "hi" == ~c"hi"
false

A charlist is just a list of integers, and IEx prints a list of printable integers as a charlist, which can be confusing: [104, 105] really is ~c"hi". Older code uses single quotes ('hi') for the same thing, and recent Elixir versions warn about that style.

When should you use a charlist? Almost never in new code. The main reason to know about them is that some Erlang libraries expect charlists, so you may need to_charlist/1 when calling them and to_string/1 on what they return. Everywhere else, use strings (binaries).

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does byte_size("hΓ©llo") return?

    The letter Γ© takes two bytes in UTF-8, so the five-letter word uses six bytes. String.length would return 5.
  2. 2. Which operator joins two strings?

    <> concatenates binaries. + is for numbers and ++ is for lists.
  3. 3. What is a string in Elixir?

    Strings are UTF-8 encoded binaries. A charlist is the list-based text type, used mainly with Erlang libraries.
  4. 4. Why does IEx print [104, 105] as ~c"hi"?

    A charlist is a list of integers. When every integer is a printable code point, the inspector shows it in the ~c form.
  5. 5. Which function should you use to show how many characters a reader sees?

    String.length/1 counts graphemes, the characters a person perceives. byte_size/1 counts bytes.

Summary

  • Strings are UTF-8 binaries in double quotes; use #{} to interpolate and <> to concatenate.
  • Heredocs (""") hold multi-line text and strip indentation based on the closing delimiter.
  • The String module returns new strings; boolean functions end with ?.
  • byte_size/1 counts bytes, while String.length/1 counts graphemes.
  • A binary is a sequence of bytes (<<104, 105>>); a string is a binary of valid UTF-8.
  • Charlists (~c"hi") are lists of code points, needed mostly for Erlang libraries.

Next: Pattern Matching: The = Operator