Sub topic 8
Iterating over bytes, chars, and graphemes
This chapter assumes you know the difference between &str and String, that Rust strings are always valid UTF-8, and that slicing uses byte offsets. You also need basic familiarity with iterators such as for, map, and collect.
A Rust string has no single "element". Depending on what you need, you can walk it as bytes, as char values, or as what a reader would call characters (grapheme clusters). Each view has its own method, item type, and cost.
Three views of the same text
- A byte is a
u8. It is the unit of storage and the unit of slice offsets. - A char is a Unicode scalar value. It is a 4-byte
charin Rust, and it takes 1 to 4 bytes inside a UTF-8 string. - A grapheme cluster is what a reader perceives as one character. It can be several
charvalues, such as a letter followed by a combining accent.
The standard library supports the first two. Graphemes need the unicode-segmentation crate.
Iterating over bytes
bytes() yields each u8 of the UTF-8 encoding. as_bytes() returns a &[u8] slice of the same data, which you can index and pass to byte-oriented APIs.
fn main() {
let s = "héllo";
for b in s.bytes() {
print!("{b:02x} ");
}
println!();
println!("{}", s.as_bytes()[1]);
}This prints 68 c3 a9 6c 6c 6f and then 195. The letter é is stored as the two bytes c3 a9, so the second byte of the string is not a letter on its own. Using the bytes of a non-ASCII string as if each were a character is a common bug.
Bytes are the right choice when you are working with ASCII-only data or a wire format. Byte literals such as b'\n' and b'=' make that kind of code readable. You can also use them for tests that are safe on UTF-8, like checking s.as_bytes()[0] == b'#'. Every byte of a multi-byte character is 128 or higher, so an ASCII byte value never appears inside one.
Iterating over chars
chars() decodes the UTF-8 and yields each char.
fn main() {
let s = "héllo";
for c in s.chars() {
print!("{c} ");
}
println!();
println!("{}", s.chars().count());
println!("{}", 'é'.len_utf8());
}The output is h é l l o, then 5, then 2. Several details matter here:
chars().count()is O(n), because Rust must decode the string to count it.len()is O(1) but returns bytes.chars()is a double-ended iterator, sorev()works.char::len_utf8()tells you how many bytes a character takes in UTF-8.- You cannot ask for the nth character in constant time. Use
s.chars().nth(n), which scans from the start.
The char type has useful classification methods, such as is_alphabetic(), is_numeric(), is_whitespace(), and is_ascii_digit(). Case conversion is subtle. to_uppercase() returns an iterator, not a single char, because one character can become several.
fn main() {
let upper: String = 'ß'.to_uppercase().collect();
println!("{upper}");
let word = "straße";
let vowels = word.chars().filter(|c| "aeiou".contains(*c)).count();
println!("{vowels}");
}This prints SS and then 2. A function that assumed one char in and one char out would be wrong for German text.
Iterating with char_indices
char_indices() yields (usize, char) pairs. The usize is the byte offset where the char starts, which is exactly what slicing needs.
fn main() {
let s = "héllo";
for (i, c) in s.char_indices() {
println!("{i}: {c}");
}
}The offsets are 0, 1, 3, 4, 5. Offset 2 is missing because it falls inside é. Every offset that char_indices produces is a valid slice boundary, so you can use it to build safe slicing helpers.
fn take_chars(s: &str, n: usize) -> &str {
match s.char_indices().nth(n) {
Some((i, _)) => &s[..i],
None => s,
}
}
fn main() {
println!("{}", take_chars("héllo", 2));
println!("{}", take_chars("hi", 10));
}This prints hé and hi. The function finds the byte offset of the char at position n and slices up to it. If the string has fewer than n + 1 chars, it returns the whole string. It never panics, because the offset always lies on a boundary.
Why chars are not always enough
A char is not necessarily what a user sees as one character. Unicode can write é as one scalar value (U+00E9) or as e followed by a combining acute accent (U+0301). Both look the same on screen. Some emoji flags are two scalar values. Counting char values then disagrees with what people count.
The grapheme view fixes this. Add the crate to Cargo.toml:
[dependencies]
unicode-segmentation = "1"Then use the UnicodeSegmentation trait:
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let s = "e\u{301}";
println!("{}", s);
println!("{}", s.len());
println!("{}", s.chars().count());
println!("{}", s.graphemes(true).count());
}The string displays as one accented letter. The three counts are 3 bytes, 2 chars, and 1 grapheme. The true argument selects extended grapheme clusters, which is the standard definition and almost always what you want.
This matters whenever you reverse text, truncate it for display, or count characters for a limit:
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let s = "e\u{301}x";
let by_char: String = s.chars().rev().collect();
let by_grapheme: String = s.graphemes(true).rev().collect();
println!("{by_char}");
println!("{by_grapheme}");
}Reversing by char moves the accent onto the x, because the accent now follows x in the output. Reversing by grapheme gives xé, keeping the accent on the e.
Choosing a view
| Method | Item type | Unit | Cost to reach the nth item |
|---|---|---|---|
| `bytes()` | `u8` | Byte | O(1) with `as_bytes()[n]` |
| `chars()` | `char` | Unicode scalar value | O(n) |
| `char_indices()` | `(usize, char)` | Scalar value plus byte offset | O(n) |
| `graphemes(true)` | `&str` | Grapheme cluster | O(n), with more work per step |
Use these rules of thumb:
- Parsing a protocol or an ASCII-only format: use
bytes(). - Classifying or transforming individual characters, such as checking digits or letters: use
chars(). - Needing positions to slice or report errors: use
char_indices(). - Showing text to people, such as reversing, truncating, or counting visible characters: use graphemes.
Grapheme segmentation is not free. It consults Unicode tables on every step, so avoid it in hot loops where chars() is sufficient. Even graphemes do not equal display width. East Asian characters can take two terminal columns, which needs a separate crate such as unicode-width.
Common mistakes
- Treating
len()as a character count. It is a byte count. - Using
bytes()for non-ASCII text. You will split characters apart. - Calling
chars().count()in a loop condition. It rescans the string on every call. Compute it once. - Writing
s.chars().nth(i)inside a loop overi. The loop becomes quadratic. Iterate once, or collect to aVec<char>if you truly need random access. - Assuming
to_uppercaseon acharreturns achar. It returns an iterator that can yield several.
Exercise
What do "héllo".len(), "héllo".chars().count(), and the largest offset yielded by "héllo".char_indices() return, and why do they differ?
Show answer
len() returns 6 because é takes two bytes in UTF-8. chars().count() returns 5, the number of Unicode scalar values. The largest offset from char_indices() is 5, the byte position where the final o starts. Offsets are in bytes, so they skip past the second byte of é, while the count is in chars.
Exercise
Why does "e\u{301}".chars().count() return 2 even though the text displays as one character, and which method reports 1?
Show answer
The string holds two scalar values, e and a combining acute accent, and chars() counts scalar values. A reader sees one grapheme cluster. The graphemes(true) method from the unicode-segmentation crate returns 1 for this string.