char_indices Yields Byte Offsets
Walk chars with byte offsets using char_indices, where multi-byte characters push offsets ahead of ordinal positions and slicing needs offsets.
Code
fn main() {
let label = "héllo ✦ rust";
// char_indices 产出 (字节偏移, 字符):多字节字符让偏移跑在序号前面
for (offset, ch) in label.char_indices().take(4) {
println!("{offset}: {ch}");
}
// 序号 2 的字符偏移已是 3(é 占 2 字节)
let at = label.char_indices().nth(2);
println!("third char: {at:?}");
// 字节偏移可用于安全切片(必须落在字符边界)
let (idx, _) = label.char_indices().nth(2).unwrap();
println!("prefix: {}", &label[..idx]);
}What the code does
Count the function main as the entire surface area of char_indices Yields Byte Offsets.
The file repeats itself only inside for (offset, ch) in label.char_indices().take(4).
Using it
Running the file prints labeled results such as third char:, prefix: — each operation’s effect is visible in the output.
Key statements
let (idx, _) = label.char_indices().nth(2).unwrap();
for (offset, ch) in label.char_indices().take(4) {
println!("{offset}: {ch}");
}
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.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 char_indices Yields Byte Offsets print when run?
- Run it as a complete program — the output lines carry labels such as `third char:`, `prefix:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.