Skip to content
Tutorials Center
My learning

Topics

Rust Reference · Primitive Types

The Rust str type

Reference for Rust's str type: UTF-8 string slices, &str literals, len, chars, bytes, slicing at char boundaries, split, trim, find, parse and comparisons.

str is Rust's primitive string slice type: a view of valid UTF-8 text stored somewhere else. It is unsized, so you meet it almost only behind a reference, as &str. String literals have type &'static str and live in the program binary. An owned, growable string is String, which dereferences to str, so every str method works on both.

Because the text is UTF-8, len() counts bytes, not characters, and you cannot index with s[i]. You can slice with byte ranges (&s[0..3]), but the ends must fall on character boundaries or the program panics.

Rust
let s: &str = "héllo";
let first_three = &s[0..3];   // "hé" (h = 1 byte, é = 2 bytes)

Try it

Rust Bytes, chars and slicing

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 Splitting, trimming, parsing and comparing

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
let a: &str = "literal";
let b: &str = &some_string[2..5];
let c: &'static str = "lives forever";
fn takes(text: &str) {}      // accepts &String as well
Method Returns
len(), is_empty() Byte length; whether it is empty.
chars(), char_indices(), bytes() Iterators over scalar values, with byte offsets, or over u8.
get(range), &s[range] Option<&str> or a slice (panics off a boundary).
starts_with, ends_with, contains, find, rfind, matches Searching with a &str, char, closure or char slice.
split, splitn, rsplit, split_once, split_whitespace, lines Splitting into &str pieces.
trim, trim_start, trim_end, trim_matches, strip_prefix, strip_suffix Removing text.
to_lowercase, to_uppercase, repeat, replace, to_owned, to_string Return a new String.
parse::<T>() Result<T, T::Err>.
as_bytes(), from_utf8(&[u8]) Conversion to and from bytes.

Panics: slicing at a position that is not a character boundary or is out of range. get never panics.

Usage notes

  • Accept &str in function parameters. A &String, &Box<str> and string literals all coerce to it.
  • Return String when the function creates new text; return &str only if it points into an input with a clear lifetime.
  • Slicing is O(1) and copies nothing; to_owned() allocates and copies.
  • chars().count() is O(n) whereas len() is O(1). chars().nth(i) is also O(n).
  • Comparison and ordering are by bytes (which equals code point order in UTF-8), not by language rules. Use a locale/collation crate for human sorting.
  • Case conversion with to_lowercase handles Unicode; to_ascii_lowercase and eq_ignore_ascii_case are the cheap ASCII-only versions.
  • Search patterns can be a &str, char, [char; N], &[char] or a closure |c| c.is_digit(10).
  • Not null-terminated. Use CStr/CString when passing text to C.