Strings and Text Processing

len()

The .len() and .is_empty() methods on str (and inherited by String via Deref) report the exact number of UTF-8 bytes in the string in $O(1)$ time.

Signatures

pub const fn len(&self) -> usize
pub const fn is_empty(&self) -> bool

Because both methods are const fn, they can be evaluated at compile time inside const and static definitions as well as at runtime.

len(), is_empty(), and capacity() on String

When working with an owned String, distinguish between its current byte length (.len()) and its allocated heap capacity (.capacity()):

Method Available On Returns Time Complexity
s.len() str and String Number of UTF-8 bytes currently in s $O(1)$
s.is_empty() str and String true if s.len() == 0 $O(1)$
s.capacity() String only Total bytes allocated on the heap (capacity >= len) $O(1)$
const HEADER: &str = "RUST-2024";
const HEADER_LEN: usize = HEADER.len(); // Evaluated at compile time

fn main() {
    println!("Const header len: {HEADER_LEN}");

    let mut buf = String::with_capacity(32);
    println!(
        "Empty buf:   len={}, is_empty={}, cap={}",
        buf.len(),
        buf.is_empty(),
        buf.capacity()
    );

    buf.push_str("payload");
    println!(
        "Filled buf:  len={}, is_empty={}, cap={}",
        buf.len(),
        buf.is_empty(),
        buf.capacity()
    );

    buf.clear();
    println!(
        "Cleared buf: len={}, is_empty={}, cap={}",
        buf.len(),
        buf.is_empty(),
        buf.capacity()
    );
}
Const header len: 9
Empty buf:   len=0, is_empty=true, cap=32
Filled buf:  len=7, is_empty=false, cap=32
Cleared buf: len=0, is_empty=true, cap=32

Prefer s.is_empty() Over s.len() == 0 or s == ""

Always use s.is_empty() (or !s.is_empty()) rather than s.len() == 0 or s == ""; it expresses intent directly and is enforced by the Clippy len_zero lint. Note that " ".is_empty() is false because three ASCII spaces occupy 3 bytes; to test whether a string contains only whitespace, use s.trim().is_empty().