Modeling Data · 16 min · free lesson

Strings & UTF-8

Rust strings are UTF-8, so there is no cheap index by character.

Core idea

len() counts UTF-8 bytes; chars().count() counts Unicode scalar values, not grapheme clusters.

Coming from C? char Arrays to Strings covers this side by side. · Coming from Node.js? UTF-16 strings vs UTF-8 String covers this side by side.

Start with the idea

String owns a growable UTF-8 buffer and &str borrows one. Rust strings do not support integer indexing such as s[0]. Choose .bytes() for encoded bytes, .chars() for Unicode scalar values, or .get(range) for a fallible byte slice. A direct invalid byte-range slice can still panic, so rejecting integer indexing does not eliminate every encoding-related mistake.

Read the code

let text = "café";
let decomposed = "e\u{301}";
assert_eq!(text.len(), 5);
assert_eq!(text.chars().count(), 4);
assert_eq!(decomposed.len(), 3);
assert_eq!(decomposed.chars().count(), 2);
assert_eq!(text.get(3..5), Some("é"));
assert_eq!(text.get(3..4), None);
println!("café: {} bytes, {} scalars", text.len(), text.chars().count());

café has five UTF-8 bytes and four scalars; the decomposed accented letter has three bytes and two scalars.

Practice starter

let word = "naïve";
let length = word.len(); // 6: this counts bytes
println!("{length}");

Practise this code in Playground ↗

Five UTF-8 bytes encode the four scalars in café; a decomposed accented letter uses two scalars for one displayed grapheme.
café has five UTF-8 bytes and four scalars; the decomposed accented letter has three bytes and two scalars.

Work through it

UTF-8 stores text as bytes, and a visible character may require more than one byte. In café, len() is five bytes, while chars().count() yields four Unicode scalar values. Neither number necessarily counts what a person sees as a grapheme: a letter plus a combining accent can be two scalar values displayed as one. Rust deliberately makes the unit explicit, so you cannot assume that the fifth byte begins a character.

A String owns and can grow its buffer. A &str borrows a valid slice of UTF-8 text, whether the source is a string literal or part of a String. Slicing by byte ranges is allowed only at character boundaries; a range ending in the middle of a multibyte character fails. Use .chars() for scalar-value iteration, .bytes() for protocol or encoding work, and .char_indices() when you need both a character and its starting byte offset. Avoid repeatedly using .chars().nth(n) as if it were constant-time indexing: it walks from the start each time.

Try printing the bytes, characters, and byte offsets of café and naïve. Predict which offsets jump by more than one. If your UI needs user-perceived character counts or cursor movement, use a Unicode grapheme library and state that requirement explicitly. For many programs, the safest first step is to ask whether the problem is about bytes, scalar values, or displayed clusters before choosing an operation.

If you must slice text, use a checked operation such as get(range) when a range may come from external input. It returns Option<&str> instead of panicking at an invalid UTF-8 boundary.

String owns growable UTF-8 bytes; &str borrows a view of UTF-8 text. A string literal has type &'static str, but a function accepting &str can also receive a borrowed view of a String. This is why read-only parameters commonly use &str: callers need not give away ownership. Appending to a String may reallocate its storage, so a reference into it cannot remain live while a mutation would invalidate that reference.

Try passing both a string literal and a borrowed String to the same read-only function. Then change the function to take String and observe the move at the call site. Use .as_str() or &value when you need a view. For slicing, remember that offsets are UTF-8 byte positions and must fall on valid character boundaries. If your task is to count or split what a human sees as characters, specify whether you mean bytes, Unicode scalar values, or grapheme clusters before writing the algorithm.

Try it

Return the first Unicode scalar of each whitespace-separated word. Preserve case and do not slice text by byte offset. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

Which expression counts Unicode scalar values in word?

Reveal the answer
  1. word.len()
  2. word.chars().count()
  3. word.bytes().len()

chars().count() decodes Unicode scalar values. len() and bytes().len() count bytes; neither is a general visible-character count.

One more experiment

Add let cafe = "cafe\u{301}"; beside text and predict its len(), its chars().count(), and cafe.get(3..5). Then explain why the two spellings can look alike and still answer differently.

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Strings & UTF-8 (courseId "basics", lessonId "strings")
Link: https://crabrix.com/learn/basics/strings/
Goal: len() counts UTF-8 bytes; chars().count() counts Unicode scalar values, not grapheme clusters.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=basics/strings) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.