Rust Reference ยท Strings and Text
Rust split_whitespace, lines and split_once
Reference for Rust str::split_whitespace, split_ascii_whitespace, lines, split_once and rsplit_once: how they treat empty pieces, CRLF and missing separators.
Besides the general split, str has helpers for the three most common jobs. split_whitespace breaks text into words and never yields empty pieces. lines breaks text into lines and understands both \n and \r\n. split_once cuts at the first occurrence of a separator and gives you both halves as an Option, which is ideal for key=value pairs.
All of them return slices (or iterators of slices) that borrow from the original string, so no allocation happens until you collect into owned strings.
let words: Vec<&str> = " hello world ".split_whitespace().collect(); // ["hello", "world"]
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_whitespace(&self) -> SplitWhitespace<'_> fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> fn lines(&self) -> Lines<'_> fn split_once<P: Pattern>(&self, delimiter: P) -> Option<(&str, &str)> fn rsplit_once<P: Pattern>(&self, delimiter: P) -> Option<(&str, &str)>
| Name | Description |
|---|---|
delimiter |
The separator: char, &str, a char array/slice or a char closure. |
Returns: split_whitespace, split_ascii_whitespace and lines return iterators of &str. split_once returns Some((before, after)) split at the first match, rsplit_once splits at the last match, and both return None when the separator does not occur. The separator itself is in neither half.
Errors / panics / edge cases: none of these panic. An empty or all-whitespace string gives an empty iterator from split_whitespace. "".lines() also yields nothing.
Usage notes
split_whitespaceuses Unicode whitespace (char::is_whitespace), including tabs, newlines and non-breaking spaces.split_ascii_whitespaceonly treats ASCII whitespace as a separator and is slightly faster on ASCII data.- Runs of whitespace collapse. Leading, trailing and repeated whitespace never produce empty strings, unlike
split(' '). linesstrips the terminator. A final line ending does not produce an extra empty line, but a blank line in the middle is kept as"". A\rthat is not followed by\nstays in the text.- Read from a file or stdin?
BufRead::linesreturnsio::Result<String>items and is a different method.str::linesworks on text already in memory. split_oncesplits only once."a=b=c".split_once('=')isSome(("a", "b=c")). Usersplit_onceto cut at the last separator, for example to separate a file extension.- Combine with
?. Becausesplit_oncereturns anOption, it fits well in functions that returnOptionor, withok_or,Result. - Keep owned data when needed. The halves borrow the original string. Use
.to_string()if the pieces must outlive it.
Related
split,rsplit,splitn,trim,parse,find- Lessons: Strings, Strings overview