The Truth About Elixir Strings — Tentamen Software Testing Blog

Karlo Smid
3 min readSep 4, 2020

--

Elixir Strings As Binaries

TL;DR

In the previous post, we explained how Elixir handles fundamental computer datatype, binaries. This was a great introduction to Elixir Strings. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.

No Dedicated String Type

Elixir does not have a dedicated String Type. Instead, Strings are either Binaries or Lists.

Binary Strings (Double Quotes)

Elixir binary strings are defined using ". As in Ruby, you can embed Elixir expressions into binary strings using #{}. Character escaping works as expected. Elixir also supports multiline strings (all in the terminal screenshot above).

Elixir String sigils

Sigils are useful ~s when you have " as part of your String. It handles your error-prone character escaping. Uppercase is used for not interpreting embedded expression and not escaping characters. Heredoc is also a multiline string, and it is used for modules and function documentation. In the end, we must note the essential side effects of String binaries. Strings are concatenated in the same way as Binaries, using the <> operator.

Character Lists (Single Quotes)

Elixir String As Character List

String as a character list is defined using single quotes. We use single quotes to define character list strings. You can see that presents character list string as a list of integers. Each integer is a decimal encoding value (encoding set on your computer, in this case, this if UTF) for that character.

Binary Or Character List

Elixir prefers Binary strings. Character Lists are here just for compatibility with possible Erlang library that is using Character Lists.

List Module

Elixir List Module

The list module works with Binary Strings.

Remember

  • No dedicated String Type
  • How to use binaries for Strings
  • Embedded string expressions #{} (as in Ruby)
  • How to escape characters
  • Multiline String
  • When to use sigils, ~s() both uppercase and lowercase
  • Heredocs strings
  • String concatenation
  • How to use lists for strings
  • " and ' difference
  • When to use ~c sigils
  • Prefer Binary Strings over Character Lists
  • Use the List Module function, do not reinvent the wheel.

Originally published at https://blog.tentamen.eu on September 4, 2020.

--

--

Karlo Smid
Karlo Smid

Written by Karlo Smid

Founder of Tentamen, software testing agency.

No responses yet