Count visible text and bytes: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
Compare graphemes, code points, bytes, and a simple Unicode-aware sigil.
Measure 长安🙂 as visible characters and as bytes, then match one character.
Run this first
Run it once, change one input, and compare the new result.
Original full example
# Compare visible text with its UTF-8 bytes
text = "长安🙂"
{String.length(text), byte_size(text), String.codepoints(text), Regex.match?(~r/安/u, text)}The result is {3, 10, ["长", "安", "🙂"], true}.
Steps for the full example
- Read
String.length/1: Count graphemes in a string. - Read
byte_size/1: Count bytes in a binary. - Read
~r/.../u: Build a Unicode-aware regular expression.
Original lesson notes
Run the example first. Predict one result, then change one input and run it again.
A grapheme is one user-visible character, even when several code points build it.
A code point is one Unicode number; it is not always one visible character.
Symbols and terms
String.length/1- Count graphemes in a string.
byte_size/1- Count bytes in a binary.
~r/.../u- Build a Unicode-aware regular expression.
- grapheme
- A grapheme is one user-visible character, even when several code points build it.
- code point
- A code point is one Unicode number; it is not always one visible character.
- sigil
- A sigil begins with
~and gives a compact notation for text, regexes, dates, and other values.
Original full exercise
Split Go🙂 into graphemes and count its bytes.
Exercise starter
text = "Go🙂"
{String.____(text), ____(text)}Return {["G", "o", "🙂"], 6}.
Show hint
Use graphemes and byte_size.
Show original answer
Reference answer
text = "Go🙂"
{String.graphemes(text), byte_size(text)}Must grapheme count equal byte count?
No. UTF-8 characters can use several bytes.
Original lesson takeaways
- Use graphemes for visible text.
- Use bytes for binary sizes and protocols.
- Sigils are compact constructors, not a new data type.