char::from_u32, char::len_utf8, str::len, str::chars
pub const fn from_u32(i: u32) -> Option<char>
pub const fn len_utf8(self) -> usize
pub const fn len(&self) -> usize
pub fn chars(&self) -> Chars<'_>Build a char from a code point, and compare UTF-8 byte length with the number of scalar values. A char is not a grapheme cluster.
| Parameter | Description |
|---|---|
i | A 32-bit code point. from_u32 returns None if i is a surrogate or is greater than 0x10FFFF. |
Returns: from_u32 returns Option<char>. len_utf8 is 1 through 4. str::len is the byte length of the string. chars().count() is the number of scalar values.
- The composed "é" in this source file is a single Unicode scalar. The decomposed form is written as e plus U+0301. The counts were measured with rustc 1.90.0.
- UTF-8 slicing rules and is_char_boundary stay on the str page.
fn main() {
let thumbs = "👍";
println!("{} {}", thumbs.len(), thumbs.chars().count());
let composed = "é";
let decomposed = "e\u{0301}";
println!("{} {}", composed.len(), composed.chars().count());
println!("{} {}", decomposed.len(), decomposed.chars().count());
println!("{}", 'é'.len_utf8());
println!("{:?}", char::from_u32(0x1F44D));
println!("{:?}", char::from_u32(0xD800));
}Expected output
4 1
2 1
3 2
2
Some('👍')
NoneRelated: str byte indexes and char boundaries