Chars, Bytes & Graphemes
Iterate str as Unicode scalars (chars), raw bytes (bytes), or user-perceived grapheme clusters (crate).
Search across all documentation pages
Iterate str as Unicode scalars (chars), raw bytes (bytes), or user-perceived grapheme clusters (crate).
fn main() {
let s = "e\u{0301}"; // e + combining acute
println!("chars: {}", s.chars().count()); // may be 2
}When to reach for this: Correct length limits, cursor movement, collation - not raw bytes.
fn ascii_words(s: &str) -> impl Iterator<Item = &str> {
s.split_whitespace()
}
fn byte_len(s: &str) -> usize {
s.as_bytes().len()
}
fn main() {
let text = "Hello 世界";
println!("bytes={} chars={}", byte_len(text), text.chars().count());
for w in ascii_words(text) { println!("{w}"); }
}What this demonstrates:
chars().count() vs len() bytesas_bytes() for protocol workunicode-segmentation for UIunicode-segmentation = "1"use unicode_segmentation::UnicodeSegmentation;
for g in "👨👩👧".graphemes(true) { println!("{g}"); }&str. Fix: from_utf8 on [u8].| Alternative | Use When | Don't Use When |
|---|---|---|
unicode-segmentation | UI cursor | ASCII-only logs |
| bytes only | Binary protocol | Human text |
encode_utf16 | Windows FFI | Unix UTF-8 |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 19, 2026