Mental model
A computer cannot store "the letter é". It stores numbers, and every program that reads them has to agree on what the numbers mean. Three layers sit on top of each other:
| Layer | What it is | Example for "é" (precomposed) |
|---|---|---|
| Grapheme cluster | What a reader sees as one character | é |
| Code point | A number from the Unicode catalogue, U+0000 … U+10FFFF | U+00E9 |
| Code unit | The fixed-size piece an encoding stores: 8 bits (UTF-8), 16 bits (UTF-16), 32 bits (UTF-32) | UTF-8: C3 A9; UTF-16: 00E9 |
Usually one grapheme is one code point, and in ASCII text one code point is one byte, so the
layers blur together. They come apart as soon as text leaves English: "é" can also be written as
e + U+0301 COMBINING ACUTE ACCENT (two code points, one grapheme), an emoji like 😀 (U+1F600) is
one code point but two UTF-16 units and four UTF-8 bytes, and a flag 🇹🇷 is two code points that
render as one symbol.
Encoding a code point
The lab encodes a string one code point at a time and shows which branch of each encoder runs.
UTF-8: 1 to 4 bytes
UTF-8 splits the code point's bits over a lead byte and continuation bytes. The lead byte says how
many bytes follow; every continuation byte starts with 10.
| Code point range | Bytes | Bit layout |
|---|---|---|
| U+0000 – U+007F | 1 | 0xxxxxxx |
| U+0080 – U+07FF | 2 | 110xxxxx 10xxxxxx |
| U+0800 – U+FFFF | 3 | 1110xxxx 10xxxxxx 10xxxxxx |
| U+10000 – U+10FFFF | 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
utf8(cp):
if cp < 0x80: return [cp]
if cp < 0x800: return [0xC0 | cp >> 6, 0x80 | cp & 0x3F]
if cp < 0x10000: return [0xE0 | cp >> 12, 0x80 | (cp >> 6) & 0x3F, 0x80 | cp & 0x3F]
return [0xF0 | cp >> 18, 0x80 | (cp >> 12) & 0x3F, 0x80 | (cp >> 6) & 0x3F, 0x80 | cp & 0x3F]
Worked example: € is U+20AC = 0010 0000 1010 1100 (16 bits), so it takes three bytes. The bits
go 0010 | 000010 | 101100 into 1110xxxx 10xxxxxx 10xxxxxx: 11100010 10000010 10101100 =
E2 82 AC. Press One of each in the lab and step to the € to see the same split.
Three properties make UTF-8 the default for files and networks:
- ASCII compatible. Every ASCII file is already valid UTF-8, byte for byte.
- Self-synchronising. Continuation bytes (
10xxxxxx) can never be mistaken for a lead byte, so a reader can find the start of a character from any position, and a byte-level search for a valid UTF-8 pattern can only match at character boundaries. - No byte-order question. The unit is a byte, so there is no big-endian/little-endian variant.
UTF-16: one unit or a surrogate pair
Code points up to U+FFFF (the Basic Multilingual Plane) fit in one 16-bit unit. Larger ones are split into a surrogate pair: subtract 0x10000 to get a 20-bit number, put the top 10 bits into a high surrogate (0xD800 + …) and the bottom 10 into a low surrogate (0xDC00 + …).
utf16(cp):
if cp < 0x10000: return [cp]
v = cp - 0x10000 # 20 bits
return [0xD800 + (v >> 10), 0xDC00 + (v & 0x3FF)]
😀 = U+1F600: v = 0xF600 = 0000 1111 0110 0000 0000; the top ten bits are 0x3D and the bottom
ten 0x200, giving D83D DE00. The range U+D800–U+DFFF is reserved for these halves, which is why
those numbers are not valid code points on their own (the encoders in all four listings reject
them). A UTF-16 string that contains half a pair, a lone surrogate, cannot be converted to UTF-8.
Same text, different sizes
| Text | Code points | UTF-8 bytes | UTF-16 units |
|---|---|---|---|
Hello |
5 | 5 | 5 |
Aé€😀 |
4 | 10 | 5 |
中文 |
2 | 6 | 2 |
| 🇹🇷 | 2 | 8 | 4 |
UTF-8 is compact for Latin text; UTF-16 can be smaller for East Asian text. Neither is "one unit per character".
Grapheme clusters
A grapheme cluster is a user-perceived character: e + combining accent, a flag (two regional-indicator code points), or an emoji family joined by U+200D ZERO WIDTH JOINER. The rules for where one cluster ends are in Unicode Standard Annex #29 and change with new Unicode versions.
This is why the visualizer stops at code points. C# has StringInfo (text elements follow
grapheme rules since .NET 5), Java's BreakIterator.getCharacterInstance() approximates them,
Python's standard library has no cluster API (the third-party regex module has \X), and
standard C++ has none. A correct cross-language visualizer of clusters would need its own copy of
the segmentation data, so the lab shows the code points a cluster is made of instead; the é two
ways and ZWJ sequence presets make the difference visible.
What it means in practice: reversing a string, truncating it to "n characters" or moving a cursor should work on grapheme clusters, or the user sees broken accents and half flags.
What each language stores and counts
C# string |
Java String |
Python str |
C++ std::string |
|
|---|---|---|---|---|
| Element type | char = UTF-16 code unit |
char = UTF-16 code unit |
code point | char = byte (no encoding attached) |
Length / length() / len / size() of 😀 |
2 | 2 | 1 | 4 if it holds UTF-8 |
| Code points | EnumerateRunes(), Rune |
codePoints(), codePointAt |
iterate the str |
decode yourself or use a library |
| Can hold a lone surrogate | yes | yes | yes ("\ud800"), but encode refuses |
n/a |
- C# and Java strings are arrays of UTF-16 code units.
s[i]/s.charAt(i)is O(1) but may return half of a surrogate pair. Java stores Latin-1-only strings in one byte per character internally (compact strings), but the API still speaks UTF-16. - Python 3
stris a sequence of code points, solenand indexing count code points, and both are O(1). CPython makes that possible by storing each string with a fixed width of 1, 2 or 4 bytes per code point, chosen by the widest character in it (PEP 393).bytesis a separate type. - C++
std::stringis a byte container. It works fine for UTF-8 text as long as you remember thatsize()counts bytes ands[i]is a byte.std::u8string,std::u16stringandstd::u32stringlabel the encoding in the type but add no Unicode operations.
Indexing by character is not O(1) in UTF-8 or UTF-16: to find the k-th code point you must scan from the start, because earlier characters may take more than one unit. Only fixed-width forms (UTF-32, CPython's internal layout) give O(1) code point indexing; nothing gives O(1) grapheme indexing.
Immutability and building strings
In C#, Java and Python a string object never changes after it is created. Benefits: strings can be shared between threads and data structures without copying, used safely as hash keys (the hash can be cached), and passed around without defensive copies. The cost: every "modification" creates a new string.
So this loop is quadratic:
s = ""
for each of n pieces:
s = s + piece # copies everything built so far
The i-th concatenation copies about i pieces, so the total is 1 + 2 + … + n ≈ n²/2 copies. The fix is a growable buffer, the dynamic array from the arrays module, with amortised O(1) append:
| Language | Build a string from many pieces | Notes |
|---|---|---|
| C# | var sb = new StringBuilder(); sb.Append(piece); sb.ToString() |
string.Join / string.Concat for a known sequence |
| Java | var sb = new StringBuilder(); sb.append(piece); sb.toString() |
String.join; the compiler already uses a builder for a + b + c in one expression, not across loop iterations |
| Python | parts.append(piece) then "".join(parts) |
CPython sometimes optimises s += piece in place, but that is an implementation detail, not a guarantee |
| C++ | s += piece or s.append(piece) |
std::string is mutable and grows like std::vector; call reserve if you know the size |
In C++ the question is reversed: std::string is mutable and copied by value, so pass
const std::string& or std::string_view to avoid copies.
Comparison and equality
- Ordinal comparison compares code units (C#, Java), code points (Python) or bytes (C++). It is fast and predictable, and it is what hashing and the string-matching lesson use. Note that UTF-16 ordinal order differs from code point order above U+FFFF, because surrogates (D800–DFFF) sort below U+E000–U+FFFF.
- Culture-aware comparison (C#
StringComparison.CurrentCulture, JavaCollator, ICU) sorts the way people expect in a language, for example "ä" next to "a" in German. - Normalisation. Precomposed é (U+00E9) and e + U+0301 compare unequal ordinally. Normalise both
sides first (NFC or NFD) when the text comes from different sources:
string.Normalize(),java.text.Normalizer,unicodedata.normalize, or ICU in C++.
The teaching implementation
Utf8Bytes / utf8_bytes and Utf16Units / utf16_units are written the same way in all four
languages. Each language reads one shared fixture (every length boundary, U+D7FF and U+E000 around
the surrogate block, U+FFFF, U+10000, U+10FFFF, combining marks, a flag, a ZWJ sequence) and checks
5,000 random code points against its built-in encoder: Encoding.UTF8 and char.ConvertFromUtf32
in C#, str.encode in Python, getBytes(UTF_8) and Character.toChars in Java. Standard C++ has
no UTF-8 converter any more (std::codecvt_utf8 was deprecated in C++17 and removed in C++26), so
the C++ test round-trips through independent decoders and compares with u8"…" and u"…" literals.
Common mistakes
- Using
Lengthas "number of characters" for user-facing limits. An emoji counts 2 in C# and Java, 1 in Python and 4 in a UTF-8std::string. - Cutting a string at an arbitrary index. In UTF-16 you can split a surrogate pair; in UTF-8 you can split a multi-byte sequence; in any encoding you can split a grapheme cluster.
- Reversing code units. Reversing
D83D DE00givesDE00 D83D, which is invalid. - Assuming one byte per character when sizing buffers for UTF-8: allow up to 4 bytes per code point (3 per UTF-16 unit).
- Concatenating in a loop with
+in C#, Java or Python. - Comparing user input without normalising it.
Edge cases
- The empty string: zero code points, zero bytes, zero units.
- U+0000 is a valid code point (one byte
00); C APIs that use NUL-terminated strings cannot hold it. - Code points just below and above the surrogate range (U+D7FF, U+E000) are ordinary 3-byte characters.
- U+10FFFF is the largest code point:
F4 8F BF BFin UTF-8,DBFF DFFFin UTF-16.
Worked practice
1. How many UTF-8 bytes and UTF-16 units does "naïve" take?
Answer
Five code points: n, a, ï (U+00EF), v, e. UTF-8: 1 + 1 + 2 + 1 + 1 = 6 bytes. UTF-16: 5 units, if ï is precomposed. Written as i + U+0308 it is six code points, 7 bytes and 6 units.
2. Encode U+00E9 in UTF-8.
Answer
0xE9 = 000 1110 1001 (11 bits): 00011 | 101001 into 110xxxxx 10xxxxxx gives 11000011 10101001
= C3 A9.
3. A C# method truncates a username to name.Substring(0, 10). What can go wrong?
Answer
If the 10th and 11th units form a surrogate pair, the result ends with a lone high surrogate, which
is not valid Unicode and fails when encoded to UTF-8 (or prints as a replacement character). It can
also cut a grapheme cluster in half. Truncate on text-element boundaries (StringInfo) instead.
4. Why is "".join(parts) linear but repeated s = s + p quadratic?
Answer
join first adds up the lengths, allocates the result once and copies each piece once. Repeated
+ allocates a new string every time and copies everything built so far, 1 + 2 + … + n pieces.
Summary
- Code unit, code point and grapheme cluster are different things; ASCII hides the difference.
- UTF-8 uses 1–4 bytes per code point and is ASCII compatible; UTF-16 uses one or two 16-bit units, with surrogate pairs above U+FFFF.
- C# and Java count UTF-16 units, Python counts code points, C++
std::stringcounts bytes. None of them counts grapheme clusters by default. - Strings are immutable in C#, Java and Python: build them with a builder or
join, not+in a loop.