Strings

A string in Elixir is written in double quotes and holds UTF-8 text. Under the quotes it is a binary, which is why the checks of the previous lessons call it is_binary/1, and why a byte and a character are not always the same thing. This lesson covers the quotes, interpolation, the heredoc for several lines, and the String functions a program uses every day.

A string is a binary

A double-quoted literal makes a binary of the UTF-8 bytes. Two of them join with <>, which builds a new binary; nothing is modified in place. A string is not a list of characters and not an array of bytes, so the operations on it are the functions of the String module, not an index and a loop.

greeting.exs

name = "Ada" greeting = "Hello, #{name}!" IO.puts(greeting) IO.puts("A quote: \"") IO.puts("two lines:\nsecond") IO.puts(String.length(greeting))

elixir greeting.exs

Hello, Ada!
A quote: "
two lines:
second
11

The backslash escapes the quote and writes the two control characters, and String.length/1 counts characters, not bytes. The count is 11 because the greeting has eleven characters, the exclamation mark included. The advanced strings lesson shows where the byte count differs, which is where UTF-8 matters.

Interpolation and escapes

#{ and } inside a double-quoted string run the expression between them and place its text in the string. Any expression works, including a function call and arithmetic, and the value does not need a conversion call:

interpolation.exs

age = 36 IO.puts("Next year you will be #{age + 1}") IO.puts("The name has #{String.length("Ada")} letters")

elixir interpolation.exs

Next year you will be 37
The name has 3 letters

A string with no interpolation is still a binary, and a backslash is only special inside the quotes. The escape sequences are the familiar ones: \n for a newline, \t for a tab, \ for a backslash and \" for a quote. A backslash outside a string is an operator of its own, which the functions chapter meets in default arguments.

A heredoc of several lines

Three double quotes open a heredoc, which runs to the closing three quotes on a line of its own. The newlines are part of the value, so a paragraph does not need \n between the lines. The closing quotes sit at the first column after mix format, and the text between them is kept as written:

heredoc.exs

text = """ Dear Ada, The course starts here. """ IO.puts(String.trim(text))

elixir heredoc.exs

Dear Ada,

The course starts here.

The heredoc ends with a newline, which is why String.trim/1 is there: without it, the print adds a second blank line at the end. A heredoc is the readable form of a long text, a SQL query or the body of a documentation block.

The String functions a script lives on

The String module holds the everyday tools, and each one returns a new binary. The script below trims, upper-cases, replaces, splits and searches, and ends with a single character:

functions.exs

IO.puts(" Hello " |> String.trim() |> String.upcase()) IO.puts(String.replace("a-b-c", "-", " ")) IO.inspect(String.split("one,two,three", ",")) IO.puts(String.contains?("elixir", "lix")) IO.puts(String.at("elixir", 2))

elixir functions.exs

HELLO
a b c
["one", "two", "three"]
true
i

String.split/2 returns a list, so IO.inspect/1 shows the brackets and the quotes. String.at/2 counts from zero and returns a one-character binary, which is the call an index would be in another language. String.trim/1 removes the spaces at both ends and leaves the inside alone.

The mistake: indexing a string

Square brackets after a binary do not read a character. Elixir reads them as a call to Access.get/3, which has no clause for a binary, so the program stops with a FunctionClauseError:

index.exs

IO.puts("hello"[0])

elixir index.exs

** (FunctionClauseError) no function clause matching in Access.get/3

    The following arguments were given to Access.get/3:

        # 1
        "hello"

        # 2
        0

        # 3
        nil

    Attempted function clauses (showing 6 out of 6):

        def get(-%module{} = container-, +key+, +default+)
        def get(+map+, +key+, +default+) when -is_map(map)-
        def get(+list+, +key+, +default+) when -is_list(list)- and -is_atom(key)-
        def get(+list+, +key+, +_default+) when -is_list(list)- and +is_integer(key)+
        def get(+list+, +key+, +_default+) when -is_list(list)-
        def get(-nil-, +_key+, +default+)

    (elixir 1.19.7) lib/access.ex:324: Access.get/3
    index.exs:1: (file)

The report names the six clauses Access.get/3 has, and none of them takes a binary, which is the cause in one look. The fix is String.at("hello", 0), or String.first("hello") for the first character. An index into a binary would also be ambiguous in UTF-8, where a character may take several bytes, which is why the language makes the reader choose a function by name.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What type is a double-quoted literal under the quotes?

    Answer

    A binary of UTF-8 bytes

    is_binary/1 is true for a string, and the String module works on that binary.

  2. Which operator joins two strings?

    Answer

    <>

    <> concatenates two binaries; ++ joins lists and + adds numbers.

  3. What does a heredoc keep that a quoted string does not?

    Answer

    The newlines between its lines, as part of the value

    A heredoc spans several lines and every line break is in the binary.

  4. Why does String.at("hello", 0) return a binary and not a byte?

    Answer

    A grapheme may take several bytes, so the function returns its text

    String works on characters, and one character can be more than one byte.

  5. What does this program print? IO.puts("a" <> "b")

    Answer

    ab

    The two binaries are joined into one, and IO.puts/1 prints it without quotes.

  6. What does this program print? IO.puts("2 + 2 = #{2 + 2}")

    Answer

    2 + 2 = 4

    Only the expression inside #{} is evaluated; the rest is literal text.

  7. What does this program print? IO.puts(String.upcase("mix"))

    Answer

    MIX

    String.upcase/1 returns the upper-case binary, and IO.puts/1 prints it plainly.

  8. What does this program print? IO.inspect(String.split("a,b", ","))

    Answer

    ["a", "b"]

    String.split/2 returns a list of the parts, and inspect shows its brackets and quotes.

  9. What does this program do? IO.puts("hello"[0])

    Answer

    A FunctionClauseError: Access.get/3 has no clause for a binary

    Square brackets call Access.get/3, and a binary is not a collection it can index.

  10. What does this program do? IO.puts("a" ++ "b")

    Answer

    An ArgumentError: ++ joins lists, not binaries

    The ++ operator works on lists; binaries are joined with <>.

Автор статьи: Arthur Isaev