Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Strings and Text

str len, is_empty and capacity

Reference for measuring Rust strings: str::len counts bytes, chars().count() counts characters, plus is_empty, String::capacity, reserve and shrink_to_fit.

In Rust, len() on a string returns the number of bytes of UTF-8 data, not the number of characters. For plain ASCII the two are equal, but "รฉ" has length 2 and "ๆ—ฅๆœฌ" has length 6. To count Unicode scalar values (chars) use chars().count(), which walks the whole string.

is_empty() is the cheap way to ask whether there is any text at all. String adds capacity(), the number of bytes it can hold before it must reallocate, along with reserve and shrink_to_fit to manage that space.

Rust
let s = "naรฏve";
s.len();            // 6 bytes
s.chars().count();  // 5 characters
s.is_empty();       // false

Try it

Rust Bytes versus characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Capacity management

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl str {
    pub const fn len(&self) -> usize;
    pub const fn is_empty(&self) -> bool;
}
impl String {
    pub fn capacity(&self) -> usize;
    pub fn reserve(&mut self, additional: usize);
    pub fn reserve_exact(&mut self, additional: usize);
    pub fn shrink_to_fit(&mut self);
    pub fn shrink_to(&mut self, min_capacity: usize);
}
Method Description
len() Number of bytes of UTF-8 text. O(1).
is_empty() true when len() == 0.
capacity() Bytes the String can hold without reallocating.
reserve(n) Ensures room for at least n more bytes (may allocate more).
reserve_exact(n) Asks for exactly n more where possible; the allocator may still give extra.
shrink_to_fit() Reduces capacity as close to len() as the allocator allows.
chars().count() Number of Unicode scalar values. O(n).

Returns: usize or bool. Panics: reserve panics if the new capacity would exceed isize::MAX bytes (or aborts on allocation failure).

Usage notes

  • len() is not the number of "letters". The thumbs-up with skin tone "๐Ÿ‘๐Ÿฝ" is two chars and eight bytes; combining sequences like e + U+0301 are two chars that display as one. For user-visible characters (grapheme clusters) you need a crate such as unicode-segmentation; the standard library does not provide it.
  • Never loop 0..s.len() and index into the string to process characters: use chars(), char_indices() or bytes() (iteration).
  • is_empty() is clearer than len() == 0, and Clippy suggests it.
  • Capacity is only meaningful for String. &str has a length but no capacity because it does not own its memory.
  • Don't assert exact capacities. The growth strategy is an implementation detail; test with >= as the examples do.
  • Reserve before big appends: one reserve call before a loop that adds known amounts avoids repeated reallocations. Use shrink_to_fit only when keeping a long-lived string, since it can reallocate.
  • Fixed limits such as "max 20 characters" should be validated with chars().count(), while "max 20 bytes" (for example a database column) uses len(). Decide which you mean.