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.
let mut s = String::from("Rustacean"); let last = s.pop(); // Some('n'), s == "Rustacea" s.truncate(4); // "Rust" s.clear(); // ""
Try it
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.
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
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:
removepanics ifidxis out of range (idx >= len()) or not on acharboundary.truncatepanics ifnew_lenis inside a multi-byte character; anew_lenlarger than the current length is silently ignored.drain,split_offandreplace_rangepanic if a boundary is out of range or not on acharboundary.
Usage notes
- Capacity is kept. After
clear()ortruncate(),capacity()is unchanged, which makesclearideal for reusing one buffer in a loop. Callshrink_to_fit()if memory matters. remove(0)is O(n) because the remaining bytes shift left. For repeated front removal, iterate withchars()or use aVecDeque<char>; for trimming known prefixes,strip_prefixborrows instead of mutating.popremoves achar, not a byte or a grapheme. A flag emoji or an accented letter written with combining marks takes severalpopcalls.- Dropping a
Drainremoves 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], withget(..n)for safety),trim,strip_suffixandchars().rev().skip(1)give a view or a new string; see String slicing and char boundaries. retainvisits each character once, in order, so a stateful closure (for example, deduplicating adjacent characters) is allowed because it isFnMut.- To check a boundary first, call
s.is_char_boundary(i).