Strings and binaries
| Binaries are strings | |
| Charlists | |
| Join and split | |
| Size and length |
Binaries are strings
Text in double quotes is a binary, a sequence of bytes. This is how modern Erlang stores strings, and UTF-8 text fits directly.
The double greater-than operator builds an empty binary, and the bit syntax extends it one segment at a time.
"hello".
"hello"
2> <<"hello">>.
<<"hello">>
Charlists
Text in single quotes is a charlist, a list of character codes. It is the older Erlang string style, and many library functions still speak it.
The two views hold the same text. Choose binaries for input and output, charlists only when a legacy API asks for one.
'hello'.
'hello'
2> $h.
104
Join and split
The string module joins, splits, trims, and searches. Its functions understand Unicode and return binaries.
Splitting answers with a list of binaries, one per piece, ready for the list tools of lesson 12.
string:join(["a", "b"], ",").
"a,b"
2> string:split("a,b", ",").
{<<"a">>, <<"b">>}
Size and length
byte_size counts bytes in a binary, and size works on binaries, tuples, and lists. length counts list items only.
For a UTF-8 binary the byte count can exceed the character count, so pick the measure your logic needs.
byte_size("hello").
5
2> length([a, b]).
2
Next: Truthiness: only false and nil
Article author: Arthur Isaev