Sub topic 8
Iterating over bytes, chars, and graphemes
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how Option and Result work. It also assumes you have read the earlier chapters on UTF-8 and slicing. A Rust string is a sequence of UTF-8 bytes, so "one character" can mean three different things. Rust gives you a separate iterator for each meaning.
Three levels of "character"
| Level | Method | Item type | Unit |
|---|---|---|---|
| Bytes | `s.bytes()` | `u8` | One byte of the UTF-8 encoding |
| Chars | `s.chars()` | `char` | One Unicode scalar value |
| Graphemes | external crate | `&str` | One user-perceived character |
The standard library covers the first two. Graphemes need a crate, because the rules for them live in the Unicode text segmentation standard and change between Unicode versions.
Bytes
bytes() yields each u8 of the UTF-8 data. Use it for protocols, checksums, or ASCII-only parsing.
fn main() {
for b in "hé".bytes() {
println!("{b}");
}
}This prints 104, 195, 169. The letter é takes two bytes, so it produces two items.
Chars
chars() decodes the bytes and yields one char per Unicode scalar value. A char is always 4 bytes in memory, regardless of how many bytes it takes in the string.
fn main() {
let s = "héllo";
for c in s.chars() {
println!("{c}");
}
println!("{}", s.chars().count());
}Use char_indices() when you also need the byte offset of each char. The offsets are valid slice boundaries.
fn main() {
let s = "héllo";
for (i, c) in s.char_indices() {
println!("{i}: {c}");
}
}This prints offsets 0, 1, 3, 4, 5. Offset 2 is missing because it sits inside é.
Chars are not always what readers see
Some visible characters are built from several scalar values. The letter é can be written as e followed by a combining accent (U+0301). Both forms look identical on screen.
fn main() {
let composed = "\u{e9}";
let decomposed = "e\u{301}";
println!("{} {}", composed, decomposed);
println!("{} {}", composed.chars().count(), decomposed.chars().count());
println!("{}", composed == decomposed);
}The output is é é, then 1 2, then false. The two strings look the same, yet they have different char counts and compare as unequal. Reversing such a string with chars().rev() would also attach the accent to the wrong letter.
Graphemes
A grapheme cluster is a group of scalar values that a reader treats as one character. Emoji with skin-tone modifiers and flags are common examples. The unicode-segmentation crate provides this. Add it with cargo add unicode-segmentation.
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let s = "e\u{301}a";
println!("{}", s.chars().count());
println!("{}", s.graphemes(true).count());
for g in s.graphemes(true) {
println!("{g}");
}
}The true argument asks for extended grapheme clusters, which is the standard choice. Here chars() counts 3 and graphemes(true) counts 2.
Choosing an iterator
- Use
bytes()for binary formats and ASCII-only work. - Use
chars()for per-scalar logic, such as checkingis_alphabetic(). - Use
char_indices()when you will slice afterward. - Use graphemes for anything a user sees: cursor movement, truncation to a width, reversing text.
Exercise
The string s = "ae\u{301}" is displayed as "aé". What do s.len(), s.chars().count(), and s.graphemes(true).count() return?
Show answer
s.len() is 4: a is 1 byte, e is 1 byte, and U+0301 takes 2 bytes. s.chars().count() is 3, one for each scalar value. s.graphemes(true).count() is 2, because e and the combining accent form one grapheme.