Rust Reference ยท Strings and Text
Rust str::split, rsplit and splitn
Reference for Rust str::split, rsplit, splitn, rsplitn, split_terminator and split_inclusive: patterns, empty pieces, limits and lazy iterators.
str::split cuts a string slice at every match of a pattern and returns a lazy iterator over the pieces. The pieces are &str slices that borrow from the original text, so nothing is copied until you call to_string() or collect into owned strings. The pattern can be a char, a &str, an array or slice of chars, or a closure that takes a char and returns bool.
The family has several variants: rsplit walks from the end, splitn and rsplitn stop after a given number of pieces, split_terminator ignores a trailing empty piece, and split_inclusive keeps the separator at the end of each piece.
let parts: Vec<&str> = "a,b,c".split(',').collect(); // ["a", "b", "c"]
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
fn split<P: Pattern>(&self, pat: P) -> Split<'_, P> fn rsplit<P: Pattern>(&self, pat: P) -> RSplit<'_, P> fn splitn<P: Pattern>(&self, n: usize, pat: P) -> SplitN<'_, P> fn rsplitn<P: Pattern>(&self, n: usize, pat: P) -> RSplitN<'_, P> fn split_terminator<P: Pattern>(&self, pat: P) -> SplitTerminator<'_, P> fn split_inclusive<P: Pattern>(&self, pat: P) -> SplitInclusive<'_, P>
| Name | Description |
|---|---|
pat |
What to split on: char, &str, &String, [char; N], &[char] or a FnMut(char) -> bool closure. |
n |
For splitn and rsplitn: the maximum number of pieces returned. The last piece holds the rest of the string, unsplit. |
Returns: an iterator of &str. With a char pattern, split, rsplit, split_terminator and split_inclusive are double-ended, so .rev() and .next_back() work; splitn and rsplitn are not.
Errors / panics / edge cases: none of these methods panic. Splitting an empty string with a non-empty pattern gives one empty piece. Splitting on the empty pattern "" yields an empty piece at the start and end, with one piece per character in between. splitn(0, ..) returns nothing.
Usage notes
- Adjacent separators produce empty pieces.
"a,,b".split(',')gives["a", "", "b"]. Filter them with.filter(|s| !s.is_empty())when they are noise. For whitespace usesplit_whitespace, which never yields empty pieces. - A trailing separator gives a trailing empty piece with
split. Usesplit_terminatorwhen each record ends with the separator, orsplit_inclusivewhen you need to keep it (for example to keep line endings). splitn(2, ..)is the classic "key=value" split that only cuts at the first separator. For this exact jobsplit_onceis shorter and returns anOption<(&str, &str)>.- Pieces borrow the source. The iterator and its items cannot outlive the original string. Call
.map(str::to_owned)or.map(String::from)to own them. - Multi-character separators are matched as a whole string, left to right, without overlapping.
"aaa".split("aa")gives["", "a"]. - Closures see one
charat a time, so they cannot match multi-character separators. - Cost: the search is linear in the length of the text; no allocation happens except when you collect.
- Regular expressions are not in the standard library. Without a crate you combine char closures,
split_onceandfind.
Related
split_whitespace,lines,split_once,trim,find,String- Lessons: Strings, Strings overview