Advanced strings in Elixir

A string in Elixir is a UTF-8 binary: a sequence of bytes that the String module reads as characters. The two views are the subject of this page, because the functions of the module count, cut and case characters while byte_size/1 counts storage, and a program that mixes the two writes text that breaks on the first accented letter.

Heredocs

Three double quotes open a heredoc, which holds several lines without the escape noise of a one-line string. The closing quotes set the indentation that is removed from every line, so a heredoc inside a function keeps the indentation of the code and not of the text:

heredoc.exs

text = """ one two """ IO.inspect(text) IO.puts(String.length(text))

elixir heredoc.exs

"one\ntwo\n"
8

The heredoc includes the newline after the last line, which is why the length is eight and the inspector shows the trailing \n. It is the form for a query, a template or a message with several lines; a short value stays in one pair of quotes.

Graphemes and bytes

String.length/1 counts graphemes, the characters a reader sees, and byte_size/1 counts the bytes of the binary. String.graphemes/1 splits into those characters and String.reverse/1 reverses them, so a composed character stays one character after the reversal:

graphemes.exs

word = "café" IO.puts(String.length(word)) IO.puts(byte_size(word)) IO.inspect(String.graphemes(word)) IO.puts(String.reverse(word)) family = "e\u0301" IO.puts(String.length(family)) IO.puts(byte_size(family))

elixir graphemes.exs

4
5
["c", "a", "f", "é"]
éfac
1
3

The word café is four characters and five bytes because the accented é takes two bytes in UTF-8. The last pair is the same letter written as e plus a combining accent: one grapheme, two code points, three bytes. A String function treats it as one character, and a function that cuts bytes does not.

Trim and pad

Trim removes whitespace from both ends or from one, and the two pad functions grow a short value to a width with a padding string. They are the pair a plain-text report is aligned with:

trim.exs

IO.inspect(String.trim(" hi ")) IO.inspect(String.trim_leading(" hi ")) IO.inspect(String.pad_leading("42", 5, "0")) IO.inspect(String.pad_trailing("ab", 5, "."))

elixir trim.exs

"hi"
"hi "
"00042"
"ab..."

String.trim/1 removes any Unicode whitespace rather than the space character alone, and String.trim/2 takes the characters to remove instead. The padding functions take a string rather than a character, repeat it as often as the width needs, and cut it when it is longer than the space.

Case and split

The case functions are Unicode aware, and the split has two forms: a separator that the program names, and no separator at all, which splits on any run of whitespace:

case.exs

IO.puts(String.upcase("ada")) IO.puts(String.capitalize("ada lovelace")) IO.inspect(String.split("a,b,c", ",")) IO.inspect(String.split("a b c"))

elixir case.exs

ADA
Ada lovelace
["a", "b", "c"]
["a", "b", "c"]

String.capitalize/1 uppercases the first character and lowercases the rest, so it is the function of a name; String.upcase/1 is the function of a constant. String.split/1 also drops leading and trailing whitespace, which makes it the right call for a line a reader typed.

inspect and the escapes

IO.inspect/2 prints a value in its source form, so a newline shows as \n and a label can go before it. IO.puts/1 prints the text itself, and String.to_integer/1 parses a number out of a string:

inspect.exs

IO.inspect("a\nb") IO.puts("a\nb") IO.inspect([1, 2, 3], label: "nums") IO.inspect(String.to_integer("42"))

elixir inspect.exs

"a\nb"
a
b
nums: [1, 2, 3]
42

The first two lines print the same value, one as source and one as text; the difference is the whole reason IO.inspect/2 exists. The label is printed before the value and the value is returned unchanged, so an inspect can sit in a pipeline while a program is being written. String.to_integer/1 raises on text that is not a number, and Integer.parse/1 is the version that answers a tuple.

The mistake: a binary cut inside a character

binary_part/3 cuts bytes, and four bytes of café end in the middle of the accented letter. The value is a binary all the same, the inspector shows its bytes, and the print fails because the bytes are not text:

mistake.exs

word = "café" part = binary_part(word, 0, 4) IO.inspect(part) IO.puts(part)

elixir mistake.exs

<<99, 97, 102, 195>>
** (ArgumentError) argument error
    (stdlib 6.2.2.5) io.erl:203: :io.put_chars(:standard_io, [<<99, 97, 102, 195>>, 10])
    mistake.exs:5: (file)

The inspector writes <<99, 97, 102, 195>> rather than the text, which is the sign that the value is no longer UTF-8: 195 is the first half of the two bytes of é and the second half is missing. The fix is String.slice/3, which cuts at character boundaries, or String.split_at/2 when the program works at a grapheme. Bytes are the unit of storage and of the network, and characters are the unit of text.

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 is the difference between String.length/1 and byte_size/1?

    Answer

    length counts graphemes, byte_size counts bytes

    A string is a UTF-8 binary, and one visible character may take several bytes.

  2. What does a heredoc keep that a one-line string does not show?

    Answer

    The newline after the last line

    The closing quotes come after a line break, so the text ends with a newline.

  3. Why does String.reverse("é") give the same letter back?

    Answer

    Because String.reverse works on graphemes

    The composed letter is one grapheme, and the String functions work on graphemes.

  4. Which function pads a number with zeros on the left?

    Answer

    String.pad_leading/3

    pad_leading grows the value on the left until it reaches the width.

  5. What does this program print? IO.puts(String.length("héllo"))

    Answer

    5

    The word has five characters, and the accented letter counts once.

  6. What does this program print? IO.puts(byte_size("héllo"))

    Answer

    6

    The accented letter takes two bytes, so the five characters are six bytes.

  7. What does this program print? IO.inspect(String.trim(" hi "))

    Answer

    "hi"

    trim removes the whitespace from both ends, and the inspector shows the quotes.

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

    Answer

    ["a", "b", "c"]

    Without a separator the split uses any run of whitespace, so the double space is one break.

  9. What does this program print? IO.inspect([1, 2, 3], label: "nums")

    Answer

    nums: [1, 2, 3]

    The label is printed before the inspected value, with a colon.

  10. What does this program do? word = "café" IO.puts(binary_part(word, 0, 4))

    Answer

    An ArgumentError, because the binary is not UTF-8 text

    Four bytes cut the accented letter in half, so the value is bytes rather than UTF-8 text.

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

Изображение баннера