Bytes Iterator For Byte Level Text
str::bytes iterates u8 while chars iterates Unicode scalars, so counts differ for multi-byte runes and len() reports the byte total directly.
Code
fn main() {
let text = "héllo";
// chars:按 Unicode 标量迭代,计数是 5
println!("chars: {}", text.chars().count());
// bytes:按 u8 迭代,é 占 2 字节,计数是 6
println!("bytes: {}", text.bytes().count());
println!("len(): {}", text.len());
// 字节级处理:ASCII 快速判断用 < 0x80
let ascii_only = text.bytes().all(|b| b < 0x80);
println!("ascii only: {ascii_only}");
// 按字节流切分时,高位字节是 UTF-8 续字节,保持原序即可
let head: Vec<String> = text.bytes().take(3).map(|b| format!("{b:#04x}")).collect();
println!("head bytes: {head:?}");
}How it works
The snippet is organized around the function main.
Caveats
- Nothing third-party is pulled in; the snippet is dependency-free.
Using it
Its full declaration is fn main()
The file announces its steps in the output: chars:, bytes:, len():.
Key statements
let head: Vec<String> = text.bytes().take(3).map(|b| format!("{b:#04x}")).collect();
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Bytes Iterator For Byte Level Text print when run?
- Running the file directly is enough — expect labeled output lines such as `chars:`, `bytes:`, `len():`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.