String::len¶
Level: reference · for working programmers
One line: The number of bytes, not characters — the same count as str::len, reached through the same deref.
Stable since 1.0.0. Usable in a const context.
String derefs to str, so this is that method; the inherent version exists so it is const and so it appears where people look for it.
It counts the UTF-8 bytes actually written — len(), not capacity(). The two differ whenever there is spare room, and only len is part of the value.
Everything the str page says applies: chars().count() is the character count and is O(n), a byte offset is not a character position, and this is the number a slice endpoint is measured in.
Example¶
string_len.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let s = String::from("héllo");
println!("len {} chars {}", s.len(), s.chars().count());
// len is what is written; capacity is what is available.
let mut roomy = String::with_capacity(64);
roomy.push_str("héllo");
println!("len {} capacity {}", roomy.len(), roomy.capacity());
// The same count as the str method.
println!("{}", s.len() == s.as_str().len());
// Bytes grow by more than one per character.
let mut built = String::new();
for c in ['a', 'é', '👋'] {
built.push(c);
println!("after {c:?}: len {}", built.len());
}
}
Verified output of string_len.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
str::len— the full explanation of what is being countedString::is_empty— the== 0testString::capacity— the other number, which is not the valuestr::chars— the character count instead
String::len in the standard library ↗
Po polsku¶
len liczy bajty, nie znaki, a dla polskiego tekstu ta różnica przestaje być teoretyczna już przy pierwszym słowie: "Zażółć".len() to 10, podczas gdy "Zażółć".chars().count() to 6, bo ż, ó, ł i ć zajmują po dwa bajty każdy — dokładnie to samo, co strona pokazuje na "héllo" wierszem len 6 chars 5. Kto przychodzi z Pythona, gdzie len("Zażółć") daje po prostu 6, musi tę intuicję odwrócić: w Ruscie długość w znakach liczy się jawnie, przez chars().count(), i jest to operacja O(n), bo trzeba przejść cały łańcuch znaków od początku. Nie myl też len() z capacity() — pierwsze mówi, ile treści jest zapisanej, i należy do wartości; drugie mówi tylko, ile miejsca wynajęto na stercie (stąd len 6 capacity 64 w przykładzie).
Szukaj po polsku: długość łańcucha w bajtach · polskie znaki w UTF-8 · liczba znaków a liczba bajtów · rust String len bytes not chars · rust chars count