Start with the idea
Rust str is valid UTF-8. len counts bytes, and chars iterates Unicode scalar values. Neither operation counts user-perceived grapheme clusters in general. A decomposed accent can consist of two scalar values while users perceive one letter. Emoji can occupy several UTF-8 bytes and two UTF-16 code units even before considering combined sequences.
String slicing uses byte offsets and requires valid UTF-8 boundaries. get returns None for an invalid range instead of panicking through indexing. char_indices supplies byte offsets at scalar boundaries; those positions are still not necessarily grapheme boundaries. The example uses a two-byte accented letter and checks both the valid whole-letter range and an invalid split.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 754 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.