Chars Count Versus Byte Len
String len() counts UTF-8 bytes while chars().count() counts characters, and the gap decides password limits and text truncation.
Code
fn main() {
let label = "café";
let emoji = "🦀";
// len() counts UTF-8 bytes versus chars().count(), which counts characters
println!("{}: {} bytes", label, label.len());
println!("{}: {} chars", label, label.chars().count());
println!("{}: {} bytes", emoji, emoji.len());
println!("{}: {} chars", emoji, emoji.chars().count());
// char_indices exposes the real byte offset of each character
for (byte_at, ch) in label.char_indices() {
println!("byte {byte_at}: {ch}");
}
}How it works
Chars Count Versus Byte Len reduces to the function main.
Iteration happens inside for (byte_at, ch) in label.char_indices() — everything outside it runs once.
Putting it to use
Output lines are prefixed (byte), making each step’s effect easy to spot.
Core lines
let label = "café";
let emoji = "🦀";
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.
FAQ
- What does Chars Count Versus Byte Len print when run?
- No setup needed: run the file and look for labeled lines like `byte` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.