Skip to content
Tutorials Center
My learning

Topics

Rust Reference · Strings and Text

Rust string slicing and char boundaries

Reference for slicing Rust strings: byte ranges, panics off a char boundary, str::get, is_char_boundary, split_at and floor_char_boundary alternatives.

You can slice a String or &str with a range, &s[2..5], to get a &str that borrows part of the text. The range is measured in bytes, not characters, and both ends must fall on character boundaries. If one does not, the program panics at run time.

For fallible slicing use get, which returns None instead of panicking. is_char_boundary tells you whether an offset is legal, and split_at cuts a string into two halves at a boundary.

Rust
let s = "hello world";
let hello = &s[..5];
let world = &s[6..];

Try it

Rust Safe and unsafe 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 A slice off a boundary panics

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
&s[a..b]  &s[a..]  &s[..b]  &s[..]  &s[a..=b]
fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output>
fn is_char_boundary(&self, index: usize) -> bool
fn split_at(&self, mid: usize) -> (&str, &str)
fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)>
Name Description
a, b Byte offsets. The slice covers a up to but not including b (a..=b includes b).
index, mid A byte offset into the string.

Returns: a &str borrowing part of the original. get returns Option<&str>; split_at_checked returns Option<(&str, &str)>.

Errors / panics / edge cases: indexing and split_at panic when an offset is greater than len(), when start is greater than end, or when an offset is not on a character boundary. The message names the character that straddles the offset, for example "end byte index 3 is not a char boundary; it is inside 'ï' (bytes 2..4 of string)". get and split_at_checked return None in all those cases.

Usage notes

  • Offsets are bytes. In ASCII text they equal character positions; in other text they do not. 'é' takes two bytes, '€' three, most emoji four.
  • Offset len() is valid, and &s[len..] is the empty string. 0 and len() are always boundaries.
  • Get offsets from the string itself. Values from find, char_indices and rfind are always boundaries; numbers you computed by hand may not be.
  • A single index like s[2] is a compile error. Strings cannot be indexed by integer, precisely because that would hide this cost and ambiguity. Use chars().nth(2) or as_bytes()[2].
  • Slicing is O(1) and does not copy; the slice just stores a pointer and a length. Checking the boundary looks at one or two bytes.
  • Taking the first N characters needs char_indices: s.char_indices().nth(n).map_or(s, |(i, _)| &s[..i]).
  • Slices borrow. You cannot modify or drop the original String while a slice of it is alive; call to_string() if you need an owned copy.
  • Rounding to a boundary. When you must cut at "about N bytes" (for example to truncate for display), loop down with while !s.is_char_boundary(n) { n -= 1; }; this works on every Rust version.
  • &s[a..=b] includes byte b, so the end offset checked is b + 1.