← Fundamentals
Fundamentals

Text, bytes, and Unicode

What are you counting when you ask for a string’s length?

Name the unit before counting, indexing or cutting text.

Outcome

Name the unit a string operation counts in each language, count and cut valid text by code points, and keep a UTF-8 prefix within a byte limit without splitting a code point.

Terminology (9)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Encoding
A mapping from Unicode scalar values to code-unit sequences, such as UTF-8 or UTF-16.
Code unit
The storage unit of an encoding: a byte in UTF-8, a 16-bit value in UTF-16.
Code point
One Unicode number, written U+0000 to U+10FFFF, such as U+00E9 for é.
Unicode scalar value
A code point outside U+D800 through U+DFFF, the surrogate range. Rust char represents scalar values.
UTF-8
An encoding of each Unicode scalar value in one to four bytes; ASCII stays one byte.
UTF-16
An encoding of each Unicode scalar value in one or two 16-bit units.
Surrogate pair
Two UTF-16 units that together encode one code point above U+FFFF.
Grapheme cluster
What a reader perceives as one character; it can contain several code points.
Continuation byte
A UTF-8 byte of the form 10xxxxxx, which continues a multi-byte sequence.

Bytes, code points and visible symbols

Unicode assigns numbers called code points to text elements. An encoding such as UTF-8 or UTF-16 represents them using bytes or code units. A grapheme cluster groups code points into a unit readers commonly perceive as one symbol; it can contain more than one code point.

Length, iteration and slicing need not use the same unit. A byte budget, a code-point limit and a visible-symbol preview are different contracts. Identify the selected API’s unit and valid boundaries before applying an index from one operation to another.

01Length

Each language’s length counts a different unit

A notification service reports message length in Unicode code points. Its preview must keep a requested number of those points, while the push gateway limits UTF-8 bytes. The same text passes through all three operations. Check what the language’s default length measures before using it for the service’s counter.

Use café 🙂 to check the counter: it includes an accented letter and an emoji. The service asks for code points, but the default length operation may count another unit. Predict what this operation reports before choosing it for the counter.

std::string holds bytes. The lab compiler stores these string literals as UTF-8.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <string>

int main() {
    std::string label = "café 🙂";

    std::cout << label.size() << '\n';
}
What does the program print?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main

Use the selected language’s setup from the first reading and replace the file for each experiment. Save source files as UTF-8; the C++ target also uses UTF-8 for ordinary string literals and 8-bit char units. Service inputs in this lesson are valid UTF-8, with nonnegative whole-number limits. Malformed-input validation and grapheme-preserving previews are separate requirements.

02Code points and graphemes

One visible symbol can be several code points

A notification can include 👍🏽. The service contract counts code points, even when several draw as one symbol. A code point is a Unicode number, such as U+1F44D for 👍; the skin-tone modifier has its own number. Measure this message fragment to distinguish the policy from a visible-symbol counter.

The program prints the size and each byte in hexadecimal. The standard library has no code-point or grapheme counting for std::string.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iomanip>
#include <iostream>
#include <string>

int main() {
    std::string thumbs = "👍🏽";

    std::cout << thumbs.size() << ':';

    for (unsigned char byte : thumbs) {
        std::cout << ' ' << std::hex << std::setw(2) << std::setfill('0') << +byte;
    }

    std::cout << '\n';
}
How many code points do the eight printed bytes encode?
Loading Eight bytes, two code points, one symbol…

03Iterating

Loops and indexes use the string’s own unit

The preview receives a limit in code points, but native slices may expect a different index. Walk through 🙂! to find how a point’s position maps to those indexes. Predict the positions, or the loop’s step count in C++.

A range-for over std::string visits each char. The program counts the steps instead of positions.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <string>

int main() {
    std::string text = "🙂!";
    int steps = 0;

    for ([[maybe_unused]] char unit : text) {
        ++steps;
    }

    std::cout << steps << '\n';
}
How many steps does the loop take?

04Slicing

A slice can end inside a character

Try the preview’s simplest candidate: keep the first native unit of 🙂 ok. The result tests whether the slicing API protects point boundaries or leaves that job to the caller. Predict what the cut produces.

substr(0, 1) keeps one byte; the program prints its size and its value in hexadecimal.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <string>

int main() {
    std::string text = "🙂 ok";
    std::string cut = text.substr(0, 1);

    std::cout << cut.size() << ' ' << std::hex << +static_cast<unsigned char>(cut[0])
              << '\n';
}
What does keeping the first unit produce?

05Repair the notifications

Count, preview, then fit a byte budget

Repair the same notification service’s counter, preview and sender. Here characters means Unicode code points, not grapheme clusters. Count each message, construct a prefix with a requested point count, then keep the longest prefix that fits a UTF-8 byte budget. Inputs are valid UTF-8 and limits are nonnegative whole numbers.

The lab opens in your reading language and has its own language control. Each file contains its imports, types, reader and complete main. Later levels supply the earlier correct helpers.

Repair the notification tool

Counting code points, cutting by code points, then cutting by bytes without splitting a character.

  1. easy · F-TEXT-V4-1 Count the characters
  2. medium · F-TEXT-V4-2 Preview a message
  3. hard · F-TEXT-V4-3 Fit the byte budget
In the frontend Does a textarea limit enforce the service’s code-point policy? Optional

The web composer labels its limit as 80 code points. These candidates bind the message to a textarea and set its native maximum length to 80. Check whether the browser attribute measures the same unit as the service.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

import { useState } from "react";

export default function NotificationComposer() {
  const [message, setMessage] = useState("");

  return (
    <label>
      Notification (80 code points)
      <textarea
        maxLength={80}
        value={message}
        onChange={(event) => setMessage(event.target.value)}
      />
    </label>
  );
}

React’s value and onChange keep the message in component state. They do not change HTML maxlength’s UTF-16 code-unit measurement. Forty 🙂 code points occupy 80 units, so the native limit and the label describe different policies. The attribute governs user input; it is not a replacement for the service’s own code-point validation.

Sources: HTML: limiting user input length,React: textarea,Svelte: bind:value.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.