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.

RustData Integrity

Code

rustsnippet
17 lines
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

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():`.