Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Strings and Text

String pop, remove, truncate and clear

Reference for removing text from a Rust String: pop, remove, truncate, clear, drain, retain, split_off and replace_range, with byte-offset rules.

A String can shrink as well as grow. pop removes and returns the last character. remove(i) removes and returns the character that starts at byte offset i. truncate(n) cuts the string down to n bytes, clear empties it, and drain(range) removes a range and hands the removed text back as an iterator. retain keeps only the characters that satisfy a predicate.

None of these shrink the allocation: the capacity stays the same until you call shrink_to_fit.

Rust
let mut s = String::from("Rustacean");
let last = s.pop();      // Some('n'), s == "Rustacea"
s.truncate(4);           // "Rust"
s.clear();               // ""

Try it

Rust Removing characters and ranges

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 retain, split_off and replace_range

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 String {
    pub fn pop(&mut self) -> Option<char>;
    pub fn remove(&mut self, idx: usize) -> char;
    pub fn truncate(&mut self, new_len: usize);
    pub fn clear(&mut self);
    pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> Drain<'_>;
    pub fn retain<F: FnMut(char) -> bool>(&mut self, f: F);
    pub fn split_off(&mut self, at: usize) -> String;
    pub fn replace_range<R: RangeBounds<usize>>(&mut self, range: R, replace_with: &str);
}
Name Description
idx, at, new_len Byte offsets, not character counts.
range A byte range such as 2..5, ..3 or 7...
f A closure called once per char; return true to keep it.

Returns: pop gives Option<char> (None when empty). remove gives the removed char. split_off gives the tail as a new String. drain gives an iterator over the removed chars. The others return nothing.

Panics:

  • remove panics if idx is out of range (idx >= len()) or not on a char boundary.
  • truncate panics if new_len is inside a multi-byte character; a new_len larger than the current length is silently ignored.
  • drain, split_off and replace_range panic if a boundary is out of range or not on a char boundary.

Usage notes

  • Capacity is kept. After clear() or truncate(), capacity() is unchanged, which makes clear ideal for reusing one buffer in a loop. Call shrink_to_fit() if memory matters.
  • remove(0) is O(n) because the remaining bytes shift left. For repeated front removal, iterate with chars() or use a VecDeque<char>; for trimming known prefixes, strip_prefix borrows instead of mutating.
  • pop removes a char, not a byte or a grapheme. A flag emoji or an accented letter written with combining marks takes several pop calls.
  • Dropping a Drain removes the range even if you did not iterate it. If you leak the iterator (mem::forget), the string may be left shortened, but never invalid.
  • Alternatives that don't mutate: slicing (&s[..n], with get(..n) for safety), trim, strip_suffix and chars().rev().skip(1) give a view or a new string; see String slicing and char boundaries.
  • retain visits each character once, in order, so a stateful closure (for example, deduplicating adjacent characters) is allowed because it is FnMut.
  • To check a boundary first, call s.is_char_boundary(i).