Strings and binaries
Strings are lists
Text in double quotes is a string, and a string in Erlang is a list of character codes. The shell prints a printable list back in quotes, so the same list can be typed either way. That is not a convenience of the shell: the compiler stores the string as the list, and every list function works on it.
erl
1> "hello". "hello" 2> [104, 101, 108, 108, 111]. "hello" 3> hd("hello"). 104 4> $h. 104
A string is a list, so hd/1 gives its first code and the list functions of the Lists lesson work on it. Single quotes build an atom instead: 'hello' is the atom hello, not the text. That mix-up is the first bug of a beginner who comes from a language where both quote styles mean a string.
Binaries
A binary is a sequence of bytes between double angle brackets. It is the compact form for text that arrives from a file or a socket, and UTF-8 text fits directly. The two forms are different values: a string is a list, a binary is not.
erl
1> <<"hello">>. <<"hello">> 2> <<104, 105>>. <<"hi">> 3> byte_size(<<"hello">>). 5 4> "hello" =:= <<"hello">>. false
The last line is the test to remember: a list and a binary that spell the same word are not equal, because their types differ. list_to_binary/1 and binary_to_list/1 convert between them, and Bit syntax builds a binary field by field.
Escape sequences
Inside a double-quoted string, a backslash starts an escape: \n is a newline, \t a tab, \" a quote and \ a backslash. The shell prints the term with ~p as a list of codes, so the escapes are visible again:
escapes.erl
-module(escapes). -export([main/0]). main() -> Text = "line one\nline two\ttabbed", io:format("~s~n", [Text]), io:format("~p~n", [Text]).
erlc escapes.erl
erl -noshell -eval 'escapes:main(), halt().'
line one line two tabbed "line one\nline two\ttabbed"
The first line of the program output is the text with the escapes applied; the last is the same list printed as a term, where ~p shows every code that is not printable. \x{1F600} writes one Unicode character by its code point, which the next section uses.
Join and split
The string module joins, splits, trims and searches. It works on strings (lists) and on UTF-8 binaries, and it counts characters rather than bytes where that matters. string:lexemes/2 splits on any run of separators and drops empty pieces, which is what a line of words needs:
erl
1> string:join(["a", "b"], ","). "a,b" 2> string:split("a,b", ","). ["a","b"] 3> string:lexemes(" one two ", " "). ["one","two"] 4> string:trim(" padded "). "padded"
string:split/2 keeps empty pieces, so string:split("a,,b", ",") has three parts. Use lexemes/2 when the extra empty strings are noise.
initials.erl
-module(initials). -export([main/0, initials/1]). first_letters([]) -> []; first_letters([Word | Rest]) -> [hd(Word) | first_letters(Rest)]. initials(Name) -> first_letters(string:lexemes(Name, " ")). main() -> io:format("~s~n", [initials("Ada Lovelace King")]).
erlc initials.erl
erl -noshell -eval 'initials:main(), halt().'
ALK
~s prints a list of codes as text, so a list of initials comes out as one string. The same two functions build a word from the first letter of every word of a sentence.
Size and length
length/1 counts the items of a list, so it counts the codes of a string. byte_size/1 counts the bytes of a binary, and size/1 does the same for a binary, a bitstring or a tuple. string:length/1 counts characters, which is what a reader sees.
erl
1> length("hello"). 5 2> size(<<"hello">>). 5 3> byte_size(<<"hello">>). 5 4> string:length(<<"héllo"/utf8>>). 5 5> byte_size(<<"héllo"/utf8>>). 6
The last two lines are the difference that bites: the word has five characters and six bytes, because é takes two bytes in UTF-8. A length limit for a column on screen counts characters, a buffer limit counts bytes.
utf8.erl
-module(utf8). -export([main/0]). main() -> Bin = <<"héllo"/utf8>>, io:format("bytes: ~w~n", [binary_to_list(Bin)]), io:format("byte count: ~p~n", [byte_size(Bin)]), io:format("character count: ~p~n", [string:length(Bin)]).
erlc utf8.erl
erl -noshell -eval 'utf8:main(), halt().'
bytes: [104,195,169,108,108,111] byte count: 6 character count: 5
~w prints the code list as plain numbers; the shell would print the same list as a string. The Encodings and Unicode lesson follows one character from these bytes to a screen, and Binaries in depth covers the binary patterns.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is an Erlang string such as
"hello"?Answer
A list of character codes
Double quotes build a list whose items are the character codes of the text.
-
What does
[104, 101, 108, 108, 111].print?Answer
"hello"The shell prints a list of printable character codes as a string in quotes.
-
How do you write a binary?
Answer
<<"hello">>Double angle brackets mark a binary, and the text inside is stored as bytes.
-
What does
'hello'.build?Answer
The atom
helloSingle quotes build an atom, never a string, so the text is a name rather than data.
-
What does
"hello" =:= <<"hello">>.return?Answer
falseA list and a binary are different types, so the strict comparison is
falseeven when the text matches. -
What does
length("hello").return?Answer
The number of items in the list
A string is a list, and
lengthcounts its items, one per character. -
For a UTF-8 binary, why can
byte_sizebe larger thanstring:length?Answer
One character may take several bytes
string:lengthcounts characters, whilebyte_sizecounts bytes; a non-ASCII character takes more than one byte. -
What does this module print?
-module(q1). -export([main/0]). main() -> io:format("~s~n", [string:join(["a", "b", "c"], "-")]).Answer
a-b-cstring:join/2puts the separator between the pieces, and~sprints the result as text. -
What does this module print?
-module(q2). -export([main/0]). main() -> Binary = <<"héllo"/utf8>>, io:format("~p~n", [{byte_size(Binary), string:length(Binary)}]).Answer
{6,5}The five characters take six bytes, because
éis two bytes in UTF-8, and the two counters answer the two questions. -
What does this module print?
-module(q3). -export([main/0]). main() -> io:format("~p~n", [byte_size(<<"héllo"/utf8>>)]).Answer
6The five characters take six bytes, because
éis two bytes in UTF-8.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev